C++ Conditional Statements: Complete Decision Making Guide
Master C++ conditional statements with comprehensive examples of if, if-else, else-if ladder, nested if, and switch statements. Learn decision-making in C++ programming with practical applications.
if Statement
Simple condition check
if-else
Two-way branching
else-if Ladder
Multiple conditions
switch-case
Multi-way selection
Understanding Conditional Statements
Conditional statements allow your program to make decisions and execute different code blocks based on certain conditions. They are fundamental to creating dynamic, responsive programs in C++.
if Simple Condition
Executes code only if condition is true. Single path decision making.
if-else Two-way Branch
Executes one block if true, another if false. Binary decision making.
else-if Multi-way Branch
Chain of conditions for multiple decision paths. Sequential checking.
switch Multi-choice
Efficient multi-way branching based on a single expression value.
Key Concepts:
- Boolean Expressions: Conditions evaluate to true (1) or false (0)
- Relational Operators:
==, !=, <, >, <=, >= - Logical Operators:
&& (AND), || (OR), ! (NOT) - Block Scope: Code blocks
{ }define scope for variables - Condition Evaluation: From top to bottom, stops at first true condition
1. Simple if Statement
// Code to execute if condition is true
}
Basic Example
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
// Simple if statement
if (number > 0) {
cout << "The number is positive." << endl;
}
// Another example with multiple conditions
int age;
cout << "\nEnter your age: ";
cin >> age;
if (age >= 18) {
cout << "You are eligible to vote!" << endl;
cout << "Please register to vote." << endl;
}
// Example with logical operators
int marks;
cout << "\nEnter your marks (0-100): ";
cin >> marks;
if (marks >= 40 && marks <= 100) {
cout << "You have passed the exam." << endl;
}
// Using relational operators
int a, b;
cout << "\nEnter two numbers: ";
cin >> a >> b;
if (a == b) {
cout << "Both numbers are equal." << endl;
}
if (a != b) {
cout << "Numbers are not equal." << endl;
}
// Checking if a number is even
if (number % 2 == 0) {
cout << number << " is an even number." << endl;
}
return 0;
}
if Statement Flowchart
Condition Check
Evaluate Expression
(Only if condition is true)
Next statements
2. if-else Statement
// Code if condition is true
} else {
// Code if condition is false
}
Basic Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Check positive or negative
int number;
cout << "Enter a number: ";
cin >> number;
if (number >= 0) {
cout << number << " is positive or zero." << endl;
} else {
cout << number << " is negative." << endl;
}
// Example 2: Check even or odd
if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
// Example 3: Voting eligibility
int age;
cout << "\nEnter your age: ";
cin >> age;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
} else {
int yearsLeft = 18 - age;
cout << "You are not eligible to vote." << endl;
cout << "Come back after " << yearsLeft << " years." << endl;
}
// Example 4: Find maximum of two numbers
int a, b;
cout << "\nEnter two numbers: ";
cin >> a >> b;
if (a > b) {
cout << a << " is greater than " << b << endl;
} else {
cout << b << " is greater than or equal to " << a << endl;
}
// Example 5: Password check
string password;
string correctPassword = "admin123";
cout << "\nEnter password: ";
cin >> password;
if (password == correctPassword) {
cout << "Access granted!" << endl;
} else {
cout << "Access denied! Incorrect password." << endl;
}
return 0;
}
Best Practices:
- Always use braces
{ }even for single statements - Keep conditions simple and readable
- Place more likely conditions first for efficiency
- Use parentheses for complex conditions for clarity
3. else-if Ladder (Multiple Conditions)
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if all conditions are false
}
Practical Examples
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Example 1: Grade Calculator
int marks;
cout << "Enter your marks (0-100): ";
cin >> marks;
cout << fixed << setprecision(2);
if (marks >= 90 && marks <= 100) {
cout << "Grade: A+" << endl;
cout << "Excellent performance!" << endl;
} else if (marks >= 80 && marks < 90) {
cout << "Grade: A" << endl;
cout << "Very good!" << endl;
} else if (marks >= 70 && marks < 80) {
cout << "Grade: B+" << endl;
cout << "Good work!" << endl;
} else if (marks >= 60 && marks < 70) {
cout << "Grade: B" << endl;
cout << "Satisfactory" << endl;
} else if (marks >= 50 && marks < 60) {
cout << "Grade: C" << endl;
cout << "Needs improvement" << endl;
} else if (marks >= 40 && marks < 50) {
cout << "Grade: D" << endl;
cout << "Barely passed" << endl;
} else if (marks >= 0 && marks < 40) {
cout << "Grade: F" << endl;
cout << "Failed" << endl;
} else {
cout << "Invalid marks! Please enter between 0 and 100." << endl;
}
// Example 2: Temperature Category
float temperature;
cout << "\nEnter temperature in Celsius: ";
cin >> temperature;
if (temperature < 0) {
cout << "Freezing cold! Wear heavy winter clothes." << endl;
} else if (temperature >= 0 && temperature < 10) {
cout << "Very cold! Wear winter jacket." << endl;
} else if (temperature >= 10 && temperature < 20) {
cout << "Cold! Wear sweater." << endl;
} else if (temperature >= 20 && temperature < 30) {
cout << "Pleasant weather! Light clothes." << endl;
} else if (temperature >= 30 && temperature < 40) {
cout << "Hot! Wear summer clothes." << endl;
} else {
cout << "Extreme heat! Stay indoors if possible." << endl;
}
// Example 3: BMI Calculator
float weight, height, bmi;
cout << "\n=== BMI Calculator ===" << endl;
cout << "Enter weight (kg): ";
cin >> weight;
cout << "Enter height (m): ";
cin >> height;
bmi = weight / (height * height);
cout << "Your BMI: " << bmi << endl;
if (bmi < 18.5) {
cout << "Category: Underweight" << endl;
} else if (bmi >= 18.5 && bmi < 25) {
cout << "Category: Normal weight" << endl;
} else if (bmi >= 25 && bmi < 30) {
cout << "Category: Overweight" << endl;
} else {
cout << "Category: Obese" << endl;
}
return 0;
}
Important Notes:
- Conditions are checked from top to bottom
- Only the first true condition's block executes
- Use
elseat the end for default case - Keep conditions mutually exclusive when possible
- Avoid too many else-if levels (consider switch or other approaches)
4. Nested if Statements
// Outer if block
if (condition2) {
// Inner if block
}
}
Practical Examples
#include <iostream>
#include <string>
using namespace std;
int main() {
// Example 1: Login System
string username, password;
int attempts = 0;
const int MAX_ATTEMPTS = 3;
cout << "=== Login System ===\n";
while (attempts < MAX_ATTEMPTS) {
cout << "\nAttempt " << (attempts + 1) << " of " << MAX_ATTEMPTS << endl;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
if (username == "admin") {
if (password == "admin123") {
cout << "Login successful! Welcome Admin." << endl;
// Nested within successful login
int choice;
cout << "\n1. View Users\n2. Add User\n3. Delete User\n";
cout << "Enter choice: ";
cin >> choice;
if (choice == 1) {
cout << "Displaying users..." << endl;
} else if (choice == 2) {
cout << "Adding user..." << endl;
} else if (choice == 3) {
cout << "Deleting user..." << endl;
} else {
cout << "Invalid choice!" << endl;
}
break;
} else {
cout << "Incorrect password!" << endl;
}
} else {
cout << "Invalid username!" << endl;
}
attempts++;
if (attempts == MAX_ATTEMPTS) {
cout << "\nMaximum attempts reached. Account locked!" << endl;
}
}
// Example 2: Age and Income Check for Loan
int age;
double income;
bool hasJob;
cout << "\n=== Loan Eligibility Check ===" << endl;
cout << "Enter your age: ";
cin >> age;
if (age >= 21) {
cout << "Do you have a job? (1 for yes, 0 for no): ";
cin >> hasJob;
if (hasJob) {
cout << "Enter your annual income: $";
cin >> income;
if (income >= 30000) {
cout << "Enter your credit score: ";
int creditScore;
cin >> creditScore;
if (creditScore >= 650) {
cout << "Congratulations! You are eligible for a loan." << endl;
if (income > 50000) {
cout << "You qualify for premium loan rates!" << endl;
}
} else {
cout << "Sorry, your credit score is too low." << endl;
}
} else {
cout << "Sorry, minimum income requirement is $30,000." << endl;
}
} else {
cout << "Sorry, you need to be employed to get a loan." << endl;
}
} else {
cout << "Sorry, minimum age requirement is 21 years." << endl;
}
// Example 3: Number Classification
int num;
cout << "\nEnter a number: ";
cin >> num;
if (num != 0) {
if (num > 0) {
cout << num << " is positive" << endl;
if (num % 2 == 0) {
cout << "and even." << endl;
} else {
cout << "and odd." << endl;
}
} else {
cout << num << " is negative" << endl;
if (num % 2 == 0) {
cout << "and even." << endl;
} else {
cout << "and odd." << endl;
}
}
} else {
cout << "The number is zero." << endl;
}
return 0;
}
Avoid Deep Nesting:
- Deeply nested code (more than 3 levels) is hard to read and maintain
- Consider refactoring with functions or early returns
- Use logical operators (
&&,||) to combine conditions - Keep nesting shallow for better code readability
5. Switch Statement
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
break;
}
Comprehensive Examples
#include <iostream>
#include <string>
using namespace std;
int main() {
// Example 1: Simple Calculator
char operation;
double num1, num2, result;
cout << "=== Simple Calculator ===" << endl;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
cout << "Enter second number: ";
cin >> num2;
switch (operation) {
case '+':
result = num1 + num2;
cout << num1 << " + " << num2 << " = " << result << endl;
break;
case '-':
result = num1 - num2;
cout << num1 << " - " << num2 << " = " << result << endl;
break;
case '*':
result = num1 * num2;
cout << num1 << " * " << num2 << " = " << result << endl;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
cout << num1 << " / " << num2 << " = " << result << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
default:
cout << "Error: Invalid operation!" << endl;
break;
}
// Example 2: Menu Driven Program
int choice;
cout << "\n=== Restaurant Menu ===" << endl;
cout << "1. Pizza - $12.99" << endl;
cout << "2. Burger - $8.99" << endl;
cout << "3. Pasta - $10.99" << endl;
cout << "4. Salad - $6.99" << endl;
cout << "5. Drink - $2.99" << endl;
cout << "Enter your choice (1-5): ";
cin >> choice;
switch (choice) {
case 1:
cout << "You ordered: Pizza - $12.99" << endl;
break;
case 2:
cout << "You ordered: Burger - $8.99" << endl;
break;
case 3:
cout << "You ordered: Pasta - $10.99" << endl;
break;
case 4:
cout << "You ordered: Salad - $6.99" << endl;
break;
case 5:
cout << "You ordered: Drink - $2.99" << endl;
break;
default:
cout << "Invalid choice! Please select 1-5." << endl;
break;
}
// Example 3: Day of Week
int dayNumber;
cout << "\nEnter day number (1-7): ";
cin >> dayNumber;
switch (dayNumber) {
case 1:
cout << "Monday - Start of work week" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday - Mid week" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday - Last work day" << endl;
break;
case 6:
cout << "Saturday - Weekend!" << endl;
break;
case 7:
cout << "Sunday - Weekend!" << endl;
break;
default:
cout << "Invalid day! Please enter 1-7." << endl;
break;
}
// Example 4: Grade with switch (char)
char grade;
cout << "\nEnter your grade (A, B, C, D, F): ";
cin >> grade;
switch (toupper(grade)) {
case 'A':
cout << "Excellent! Keep it up." << endl;
break;
case 'B':
cout << "Very good!" << endl;
break;
case 'C':
cout << "Good. Room for improvement." << endl;
break;
case 'D':
cout << "You passed, but need to work harder." << endl;
break;
case 'F':
cout << "Failed. Please try again." << endl;
break;
default:
cout << "Invalid grade entered." << endl;
break;
}
// Example 5: Multiple cases for same code (C++17 and above)
int month;
cout << "\nEnter month number (1-12): ";
cin >> month;
switch (month) {
case 12:
case 1:
case 2:
cout << "Winter season" << endl;
break;
case 3:
case 4:
case 5:
cout << "Spring season" << endl;
break;
case 6:
case 7:
case 8:
cout << "Summer season" << endl;
break;
case 9:
case 10:
case 11:
cout << "Autumn/Fall season" << endl;
break;
default:
cout << "Invalid month!" << endl;
break;
}
return 0;
}
Switch Limitations & Rules:
- Switch expression must be integral or enumeration type (int, char, enum)
- Case values must be constant expressions (not variables)
breakis optional but usually needed to prevent fall-throughdefaultcase is optional but recommended- Each case creates its own block scope (variables need to be in blocks)
6. Ternary (Conditional) Operator
condition ? expression1 : expression2
// Equivalent to:
if (condition) {
expression1;
} else {
expression2;
}
Examples
#include <iostream>
#include <string>
using namespace std;
int main() {
// Example 1: Find maximum of two numbers
int a = 10, b = 20;
int max = (a > b) ? a : b;
cout << "Maximum of " << a << " and " << b << " is: " << max << endl;
// Example 2: Check even or odd
int num;
cout << "Enter a number: ";
cin >> num;
string result = (num % 2 == 0) ? "even" : "odd";
cout << num << " is " << result << endl;
// Example 3: Absolute value
int value = -15;
int absolute = (value < 0) ? -value : value;
cout << "Absolute value of " << value << " is: " << absolute << endl;
// Example 4: Grade pass/fail
int marks;
cout << "Enter marks: ";
cin >> marks;
string status = (marks >= 40) ? "Pass" : "Fail";
cout << "Status: " << status << endl;
// Example 5: Nested ternary (use cautiously!)
int x = 10, y = 20, z = 30;
int largest = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
cout << "Largest of " << x << ", " << y << ", " << z << " is: " << largest << endl;
// Example 6: Initialize variable based on condition
bool isMember = true;
double price = 100.0;
double discount = isMember ? 0.2 : 0.1; // 20% for members, 10% for non-members
double finalPrice = price - (price * discount);
cout << "Original price: $" << price << endl;
cout << "Discount: " << (discount * 100) << "%" << endl;
cout << "Final price: $" << finalPrice << endl;
// Example 7: Return different strings
int hour;
cout << "Enter current hour (0-23): ";
cin >> hour;
string greeting = (hour < 12) ? "Good Morning!" :
(hour < 18) ? "Good Afternoon!" : "Good Evening!";
cout << greeting << endl;
return 0;
}
Ternary Operator Warnings:
- Keep ternary expressions simple and readable
- Avoid nested ternary operators - they become hard to read
- Don't use for complex logic - use if-else instead
- Both expressions must be of compatible types
- Use parentheses for complex conditions
Comparison & Best Practices
When to Use Which Statement
| Statement | Best For | Limitations | Example Use Case |
|---|---|---|---|
| if | Single condition check | Only handles true case | Input validation, checking preconditions |
| if-else | Binary decisions (true/false) | Only two outcomes | Pass/fail, even/odd, login success/failure |
| else-if ladder | Multiple exclusive conditions | Can become long and complex | Grade systems, temperature ranges, age groups |
| nested if | Hierarchical decisions | Can become deeply nested (hard to read) | Multi-level menus, complex validation rules |
| switch | Equality checks on single expression | Only works with integral/enum types | Menu systems, day/month names, calculator operations |
| ternary operator | Simple one-liner assignments | Only two outcomes, can be hard to read | Simple value assignments, inline conditions |
Best Practices Summary:
- Always use braces
{ }even for single statements - Keep conditions simple and readable
- Avoid deep nesting - refactor into functions if needed
- Use switch for equality checks on single expressions
- Prefer if-else for range checks and complex conditions
- Document complex conditions with comments
- Test edge cases in your conditions
Practical Application: Student Management System
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
cout << "╔═══════════════════════════════════════════╗\n";
cout << "║ STUDENT MANAGEMENT SYSTEM ║\n";
cout << "╚═══════════════════════════════════════════╝\n\n";
string name;
int rollNumber, age;
float marks[5];
float total = 0, average = 0;
char grade;
// Input student details
cout << "Enter student name: ";
getline(cin, name);
cout << "Enter roll number: ";
cin >> rollNumber;
cout << "Enter age: ";
cin >> age;
// Input marks for 5 subjects
cout << "\nEnter marks for 5 subjects (out of 100):\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << (i + 1) << ": ";
cin >> marks[i];
// Validate marks
if (marks[i] < 0 || marks[i] > 100) {
cout << "Invalid marks! Enter between 0-100: ";
i--; // Retry this subject
continue;
}
total += marks[i];
}
// Calculate average
average = total / 5.0;
// Determine grade using else-if ladder
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else if (average >= 40) {
grade = 'E';
} else {
grade = 'F';
}
// Determine status using ternary operator
string status = (average >= 40) ? "PASS" : "FAIL";
// Display results
cout << fixed << setprecision(2);
cout << "\n══════════════════════════════════════════════\n";
cout << " STUDENT REPORT \n";
cout << "══════════════════════════════════════════════\n\n";
cout << left << setw(20) << "Name:" << name << endl;
cout << left << setw(20) << "Roll Number:" << rollNumber << endl;
cout << left << setw(20) << "Age:" << age << endl;
cout << "\n" << left << setw(20) << "Marks:" << endl;
for (int i = 0; i < 5; i++) {
cout << " Subject " << (i + 1) << ": " << marks[i] << endl;
}
cout << "\n" << left << setw(20) << "Total Marks:" << total << "/500" << endl;
cout << left << setw(20) << "Average:" << average << "%" << endl;
cout << left << setw(20) << "Grade:" << grade << endl;
cout << left << setw(20) << "Status:" << status << endl;
// Additional feedback based on grade
cout << "\nFeedback: ";
switch (grade) {
case 'A':
cout << "Outstanding performance! Keep it up.";
break;
case 'B':
cout << "Very good work!";
break;
case 'C':
cout << "Good performance. Room for improvement.";
break;
case 'D':
cout << "Satisfactory. Need to work harder.";
break;
case 'E':
cout << "Barely passed. Must improve.";
break;
case 'F':
cout << "Failed. Need serious improvement.";
break;
}
cout << endl;
// Check for scholarship eligibility
cout << "\nScholarship Eligibility: ";
if (age >= 18 && age <= 25) {
if (average >= 85) {
cout << "Eligible for Merit Scholarship!";
} else if (average >= 75 && total < 30000) { // Assuming family income check
cout << "Eligible for Need-Based Scholarship!";
} else {
cout << "Not eligible for scholarship.";
}
} else {
cout << "Age criteria not met for scholarships.";
}
cout << endl;
cout << "\n══════════════════════════════════════════════\n";
cout << "Thank you for using Student Management System!\n";
return 0;
}
Quick Quiz: Test Your Knowledge
What will be the output of this code?
int x = 5, y = 10;
if (x > y) {
cout << "X is greater";
} else if (x == y) {
cout << "Equal";
} else {
cout << "Y is greater";
}
Summary & Key Takeaways
Do's
- Always use braces for code blocks
- Keep conditions simple and readable
- Use comments for complex conditions
- Test all possible paths (edge cases)
- Choose the right statement for the job
Don'ts
- Don't create deeply nested structures
- Avoid complex conditions in one line
- Don't forget break in switch cases
- Avoid unnecessary else blocks
- Don't use switch for range checks
Final Thoughts
Conditional statements are the backbone of decision-making in C++ programming. Mastering if, else-if, nested if, and switch statements is essential for writing dynamic and responsive programs. Remember that clarity and readability are more important than clever one-liners. Practice with different scenarios to build your intuition for choosing the right conditional structure for each situation.