Topic 2.3 — if Statements

Goal: write and trace if statements (with and without else), and connect boolean expressions to decision-making in code.

The big idea

An if statement lets your program choose what to do based on a boolean condition. If the condition is true, the “then” part runs. If it’s false, it’s skipped (or the else part runs if you have one).

Basic structure

if (condition) {
  // runs when condition is true
}

The condition must be a boolean expression (true/false).

if with else

Use else when you want exactly one of two paths to run.

if (score >= 70) {
  grade = "pass";
} else {
  grade = "retry";
}

Tracing example (what happens?)

Always plug in values and evaluate the condition first.

int x = 5;

if (x > 10) {
  x = x + 1;
} else {
  x = x * 2;
}

// x becomes 10

Common comparison patterns

Goal Typical condition
Check if a value is in a range (x >= low) && (x <= high)
Check if two values are different x != y
Check if at least one thing is true a || b

Classic mistakes

  • Using = instead of == in a condition.
  • Forgetting braces and accidentally controlling only one line.
  • Writing a condition that is always true/false by accident.
// Only the first line is controlled by the if:
if (x > 0)
  x++;
  y++;  // this runs no matter what (oops)

Exam mindset

  • Evaluate the boolean condition first.
  • Only one branch runs in if/else.
  • Be careful with braces: they define the controlled block.
  • Use && and || for compound conditions.

Quick self-check

  1. What must the expression inside if ( ... ) evaluate to?
  2. When does the else block run?
  3. Trace: if x = 3, what happens in if (x > 3)?
  4. Write a condition for “x is between 10 and 20 inclusive.”
  5. Why are braces helpful even for one line?

← Back to Unit 2 topics