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

TEXT 📖 Display only
if (condition) {
 // code to execute when condition is true
}

Execution flow:

  1. Evaluate the condition (must be bool type or convertible to bool)
  2. If true, execute the code inside the braces
  3. If false, skip it

▶ Example 1: Check Even or Odd (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter an integer: 
 is Even
 is Odd

Run result:

TEXT 📖 Display only
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

TEXT 📖 Display only
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter an integer: 
 is Even
 is Odd

If there's only one statement after if or else, you can omit the braces:

TEXT 📖 Display only
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:

CPP
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:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter a score (0-100): 
Excellent! Grade: A
Good! Grade: B
Medium! Grade: C
Pass! Grade: D
Not Pass! Grade: F

Run result:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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):

CPP
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

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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").

CPP
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.

CPP
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

TEXT 📖 Display only
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
========== 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:

TEXT 📖 Display only
========== 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

Q Why doesn't if (x = 5) cause an error?
A The assignment expression 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.
Q Can I write an integer directly after if? Like if (5)?
A Yes. In C++, 0 is treated as false and non-zero as true. But this is not intuitive and not recommended.
Q Can switch-case check floating-point numbers?
A No. The 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.
Q Why does my if-else chain only execute the first if?
A Usually the condition is wrong or there's a brace scope issue. Debugging tip: add std::cout markers in each branch to see which one the program reaches.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that lets the user enter an integer and determines whether it's positive, negative, or zero.
TEXT 📖 Display only
Please enter an integer: -5
-5 isNegative number
  1. Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter a year and determines if it's a leap year.

  2. Leap year rule: divisible by 4 but not by 100, OR divisible by 400

  3. Implement using if-else

  4. Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "simple calculator":

  5. Let the user enter two numbers and an operator (+ - * /)

  6. Implement using switch-case

  7. If the divisor is 0, display an error

  8. If the operator is unsupported, display an error

  9. Run result:

TEXT 📖 Display only
Please enter the first number: 10
Please enter an operator: /
Please enter the second number: 3
Result: 10 / 3 = 3.33333

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!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏