C++ Conditionals

Basic if Statement

int number = 10;

if (number > 0) {
    cout << "Positive number";
}

The code block only runs if the condition is true.

if-else

int age = 17;

if (age >= 18) {
    cout << "Adult";
} else {
    cout << "Minor";
}

else if

Use else if to handle multiple conditions in sequence:

int score = 85;

if (score >= 90) {
    cout << "A";
} else if (score >= 80) {
    cout << "B";
} else {
    cout << "C or lower";
}

Nested Conditions

int temp = 20;

if (temp > 0) {
    if (temp < 30) {
        cout << "Moderate weather";
    }
}

You can place one if block inside another.

Ternary Operator

The ternary operator in C++ is a concise way to write simple if-else statements. It uses the syntax: condition ? value_if_true : value_if_false. This expression evaluates the condition and returns one of the two values based on whether the condition is true or false.

It is often used for quick decisions during variable assignment or inline output without needing full if blocks.

Example:

int score = 75;
      cout << ((score >= 60) ? "Pass" : "Fail");  // Output: Pass

Best Practices

  • Always use braces {} for clarity
  • Avoid deeply nested conditions where possible
  • Use indentation consistently

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic