C++: Conditional Statements
Last updated: 2026-08-26
In previous lessons, programs executed top to bottom with no branching.
But real programs need to "make decisions" — for example:
- If the score is >= 60, output "Passed"; otherwise output "Failed"
- If it's the weekend, go out and play; otherwise, study
That's what conditional statements are for.
1. The if Statement
(1) 1.1 Basic Syntax
if (condition) {
// code to execute when condition is true
}
Execution flow:
- Evaluate the
condition(must bebooltype or convertible tobool) - If
true, execute the code inside the braces - If
false, skip it
▶ Example 1: Check Even or Odd (Difficulty ⭐)
#include <iostream>
int main() {
int num;
std::cout << "Please enter an integer: ";
std::cin >> num;
if (num % 2 == 0) {
std::cout << num << " is Even" << std::endl;
}
if (num % 2 != 0) {
std::cout << num << " is Odd" << std::endl;
}
return 0;
}
Output:
Please enter an integer:
is Even
is Odd
Run result:
Please enter an integer: 7
7 is Odd
💡 Tip: The program above uses two if statements, but it could be simplified with if-else (see the next section).
2. The if-else Statement
(1) 2.1 Basic Syntax
if (condition) {
// execute when condition is true
} else {
// execute when condition is false
}
Key point: Exactly one of the two branches will execute, never both and never neither.
▶ Example 2: Check Even or Odd (Improved) (Difficulty ⭐)
#include <iostream>
int main() {
int num;
std::cout << "Please enter an integer: ";
std::cin >> num;
if (num % 2 == 0) {
std::cout << num << " is Even" << std::endl;
} else {
std::cout << num << " is Odd" << std::endl;
}
return 0;
}
Output:
Please enter an integer:
is Even
is Odd
(2) 2.2 Omitting Braces (Not Recommended)
If there's only one statement after if or else, you can omit the braces:
if (num % 2 == 0)
std::cout << "Even" << std::endl; // ✅ Only one statement, braces can be omitted
else
std::cout << "Odd" << std::endl;
💡 However! This is strongly discouraged — omitting braces easily leads to errors:
if (num % 2 == 0)
std::cout << "Even" << std::endl;
std::cout << "This number is divisible by 2" << std::endl; // ❌ This line always executes (indentation fooled you)
Recommended practice: Always use braces, even for a single statement.
3. The if-else if-else Chain
When there are multiple conditions to check, use else if:
if (condition1) {
// execute when condition1 is true
} else if (condition2) {
// execute when condition1 is false and condition2 is true
} else if (condition3) {
// execute when conditions 1 and 2 are false and condition3 is true
} else {
// execute when none of the above conditions are true
}
💡 Key point: Once a condition is true, the subsequent else if and else branches will not execute.
▶ Example 3: Grade Rating (Difficulty ⭐⭐)
#include <iostream>
int main() {
int score;
std::cout << "Please enter a score (0-100): ";
std::cin >> score;
if (score >= 90) {
std::cout << "Excellent! Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Good! Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Medium! Grade: C" << std::endl;
} else if (score >= 60) {
std::cout << "Pass! Grade: D" << std::endl;
} else {
std::cout << "Not Pass! Grade: F" << std::endl;
}
return 0;
}
Output:
Please enter a score (0-100):
Excellent! Grade: A
Good! Grade: B
Medium! Grade: C
Pass! Grade: D
Not Pass! Grade: F
Run result:
Please enter a score (0-100): 85
Good! Grade: B
💡 Technique: else if (score >= 80) implicitly includes the condition score < 90 (because if score >= 90 were true, the program wouldn't reach this point).
4. Nested if
An if statement can contain another if inside it — this is called nesting.
▶ Example 4: Leap Year Checker (Difficulty ⭐⭐)
#include <iostream>
int main() {
int year;
std::cout << "Please enter a year: ";
std::cin >> year;
if (year % 400 == 0) {
std::cout << year << " is a leap year" << std::endl;
} else {
if (year % 4 == 0) {
if (year % 100 != 0) {
std::cout << year << " is a leap year" << std::endl;
} else {
std::cout << year << " is not a leap year" << std::endl;
}
} else {
std::cout << year << " is not a leap year" << std::endl;
}
}
return 0;
}
Output:
Please enter a year:
is a leap year
is a leap year
is not a leap year
is not a leap year
💡 Tip: This program can be simplified using logical operators (learned in Lesson 04):
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
std::cout << year << " is a leap year" << std::endl;
} else {
std::cout << year << " is not a leap year" << std::endl;
}
5. The switch-case Statement
When the condition is an integer equality comparison, you can use switch-case instead of an if-else if chain.
(1) 5.1 Basic Syntax
switch (expression) {
case value1:
// execute when expression == value1
break;
case value2:
// execute when expression == value2
break;
...
default:
// execute when none of the above match
break;
}
▶ Example 5: Simple Calculator (Difficulty ⭐⭐)
#include <iostream>
int main() {
double num1, num2;
char op;
std::cout << "Please enter the first number: ";
std::cin >> num1;
std::cout << "Please enter an operator (+ - * /): ";
std::cin >> op;
std::cout << "Please enter the second number: ";
std::cin >> num2;
switch (op) {
case '+':
std::cout << num1 << " + " << num2 << " = " << num1 + num2 << std::endl;
break;
case '-':
std::cout << num1 << " - " << num2 << " = " << num1 - num2 << std::endl;
break;
case '*':
std::cout << num1 << " * " << num2 << " = " << num1 * num2 << std::endl;
break;
case '/':
if (num2 != 0) {
std::cout << num1 << " / " << num2 << " = " << num1 / num2 << std::endl;
} else {
std::cout << "Error: Divisor cannot be 0!" << std::endl;
}
break;
default:
std::cout << "Error: Unsupported operator!" << std::endl;
break;
}
return 0;
}
Output:
Please enter the first number:
Please enter an operator (+ - * /):
Please enter the second number:
+ =
- =
* =
/ =
Error: Divisor cannot be 0!
Error: Unsupported operator!
(2) 5.2 The Role of break
break is used to exit the switch statement. If you forget to write break, the program will continue executing the next case (this is called "fall-through").
int day = 2;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
// ❌ No break, will continue to case 2
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
}
// Output:
// Tuesday
💡 Tip: Sometimes intentionally using fall-through can simplify code (e.g., multiple cases executing the same code), but add a comment to explain.
char grade = 'B';
switch (grade) {
case 'A':
case 'B': // Intentional fall-through: A and B execute the same code
case 'C':
std::cout << "Passed!" << std::endl;
break;
case 'D':
case 'F':
std::cout << "Failed..." << std::endl;
break;
}
6. The Conditional Operator (Ternary Operator)
C++ has a "shorthand" for if-else called the ternary operator.
(1) 6.1 Basic Syntax
condition ? expression1 : expression2
Meaning: If the condition is true, return the value of expression1; otherwise return the value of expression2.
▶ Example 6: Find the Maximum Value (Difficulty ⭐)
#include <iostream>
int main() {
int a = 10, b = 20;
int max = (a > b) ? a : b; // If a > b is true, max = a; otherwise max = b
std::cout << "Maximum is: " << max << std::endl; // Output: Maximum is: 20
return 0;
}
Output:
Maximum is: 20
💡 Tip: The ternary operator is suitable for simple conditional assignments. If the logic is complex, if-else is clearer.
7. Practice: Number Guessing Game
▶ Example 7: Guess the Number (Difficulty ⭐⭐)
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
int main() {
// Use current time as random seed (covered in detail later)
std::srand(static_cast<unsigned int>(std::time(nullptr)));
int secretNumber = std::rand() % 100 + 1; // Generate random number 1-100
int guess;
int attempts = 0;
std::cout << "========== Number Guessing Game ==========\n";
std::cout << "I'm thinking of a number from 1-100. Try to guess!\n\n";
do {
std::cout << "Please enter your guess: ";
std::cin >> guess;
attempts++;
if (guess > secretNumber) {
std::cout << "Too high!Try again。\n";
} else if (guess < secretNumber) {
std::cout << "Too low!Try again。\n";
} else {
std::cout << "\n🎉 Congratulations! You got it!\n";
std::cout << "You guessed " << attempts << " time。\n";
}
} while (guess != secretNumber);
return 0;
}
Output:
========== Number Guessing Game ==========
I'm thinking of a number from 1-100. Try to guess!
Please enter your guess:
Too high!Try again。
Too low!Try again。
🎉 Congratulations! You got it!
You guessed times。
Run result:
========== Number Guessing Game ==========
I'm thinking of a number from 1-100. Try to guess!
Please enter your guess: 50
Too high!Try again。
Please enter your guess: 25
Too low!Try again。
Please enter your guess: 37
Too high!Try again。
Please enter your guess: 31
🎉 Congratulations! You got it!
You guessed 4 time。
💡 Tip: This program uses a do-while loop (covered in detail in Lesson 07) — you can copy it for now and understand the general approach.
❓ FAQ
x = 5 has the value 5 (non-zero is treated as true), so the condition is always true. Anti-bug technique: put the constant on the left — if (5 = x) will cause a compile error, if (5 == x) is correct.switch expression must be an integer type (int, char, enum). For floating-point comparisons, use if-else, and be mindful of floating-point precision issues.std::cout markers in each branch to see which one the program reaches.📖 Summary
ifchecks a condition and executes when trueif-elsehas two branches; exactly one will executeif-else if-elsechain handles multiple conditionsswitch-caseis good for integer equality comparisons; don't forgetbreak- The ternary operator
? :is a shorthand forif-else - Assignment
=and comparison==are different — don't mix them up!
📝 Exercises
- Basic (Difficulty ⭐): Write a program that lets the user enter an integer and determines whether it's positive, negative, or zero.
Please enter an integer: -5
-5 isNegative number
-
Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter a year and determines if it's a leap year.
-
Leap year rule: divisible by 4 but not by 100, OR divisible by 400
-
Implement using
if-else -
Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "simple calculator":
-
Let the user enter two numbers and an operator (+ - * /)
-
Implement using
switch-case -
If the divisor is 0, display an error
-
If the operator is unsupported, display an error
-
Run result:
Please enter the first number: 10
Please enter an operator: /
Please enter the second number: 3
Result: 10 / 3 = 3.33333
- if checks a condition and executes code block when true
- if-else has two branches; exactly one will execute
- if-else if-else chain handles multiple conditions
- switch-case handles integer multi-branch scenarios
- Conditional operator ?: simplifies simple if-else
12. 🚀 Next Step
Now that you've learned conditional statements, next we'll learn loop structures (for, while, do-while) (Lesson 07) — enabling programs to repeat code without manually writing it 100 times!