Topic 2.7 — while Loops

Goal: write and trace while loops, understand how the loop condition controls repetition, and avoid common mistakes like infinite loops and off-by-one errors.

The big idea

A while loop repeats a block of code as long as its condition is true. The condition is checked before each repetition.

Think: “Keep going while this is true.”

Structure

while (condition) {
  // repeat while condition is true
}

If the condition starts false, the loop runs 0 times.

Counting loop (classic)

This loop runs a known number of times by updating a counter.

int i = 1;
while (i <= 5) {
  sum = sum + i;
  i++;
}
  • Initialization: int i = 1;
  • Condition: i <= 5
  • Update: i++

Sentinel loop (stop when something happens)

Sometimes you don’t know how many repeats you need. You loop until a “stop signal” is reached.

// Pseudocode-style idea
while (input is not "quit") {
  process input
  get next input
}

Tracing a while loop (how to do it)

  1. Check the condition. If false → stop.
  2. If true → run the body once.
  3. Make sure something changes so the condition can eventually become false.
  4. Repeat.
int x = 3;
while (x > 0) {
  x--;
}
// Runs 3 times, then x becomes 0

Infinite loop warning

If the loop body never changes anything related to the condition, the loop may never end.

int x = 5;
while (x > 0) {
  // x never changes...
}
// infinite loop

Off-by-one errors

Using < vs <= (or starting at 0 vs 1) changes the number of repetitions.

int i = 0;
while (i < 5) {  // runs 5 times: i = 0,1,2,3,4
  i++;
}

int j = 0;
while (j <= 5) { // runs 6 times: j = 0..5
  j++;
}

Exam mindset

  • Identify the three parts: initialize → condition → update.
  • Condition checked first (so it can run 0 times).
  • Watch for infinite loops and off-by-one errors.
  • Trace carefully: update happens inside the loop body.

Quick self-check

  1. When is a while loop condition checked?
  2. Can a while loop run 0 times? When?
  3. What causes an infinite loop?
  4. How many times does this run: int i=1; while(i<4){i++;}?
  5. What’s an “off-by-one” error?

← Back to Unit 2 topics