Labs ICT
โญ Pro Login

If...Else

Making Decisions with if, else if, and else

So you want your program to think. Good choice. Conditional statements let your code take different paths depending on the situation.

The if statement runs a block only when a condition is true. Add else to catch everything else. Stack else if for multiple checks.

int score = 85;

if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
} else {
  grade = 'C';
}

Comparison Operators

Use ==, !=, <, >, <=, >= to compare values. The result is always true or false.

Nesting

You can place if statements inside other if statements. Keep nesting shallow โ€” deep nesting is hard to read.

int x = 10;
int y = 5;

if (x > 0) {
  if (y > 0) {
    cout << "Both positive";
  }
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does the following code print? int x = 10; if (x > 5) cout << "A"; else cout << "B";