2.1if/else and the three loops
The idea
A loop repeats a statement while a condition holds. for, while and do-while are three spellings of the same idea, differing in when the test happens.
Think of it like this: while is a bouncer who checks your ticket before you enter; do-while checks it after your first step inside.
Why it exists
Loop tracing is the most common skill: you keep a small table of the variables after each iteration.
How it works
- Execute the init once.
- Test the condition; if false, leave.
- Run the body (break leaves, continue skips to the step).
- Run the step (i++), then go back to the test.
Worked example: for (i = 1; i <= 4; i++) sum += i
Iterations with i = 1, 2, 3, 4 give sum = 10. The step runs once more (i becomes 5), the test fails, and the loop ends with i = 5.
Now play with it
- →Run the for loop tab and watch i and sum.
- →In the stray semicolon tab, see why the body is empty.
The step i++ runs after the body, before the next test. When the loop exits i is one past the last value.
1#include <stdio.h>2int main() {3 int sum = 0, i;4 for (i = 1; i <= 4; i++) {5 sum = sum + i;6 }7 printf("%d %d\n", sum, i);8 return 0;9}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
How many times does the body of for (i = 0; i < 10; i += 3) run?
Exam notes (the dense version)
while tests first, do-while runs the body at least once, and for(init; cond; step) is a while loop with the step run after the body. break leaves the nearest loop or switch; continue jumps to the next test (to the step in a for loop). A semicolon right after if (...) or for (...) makes the body empty.
Previous year questions: Control Flow & Output (10)
PYQs are grouped by topic, so this is the full set for Control Flow & Output; try the ones that match this subtopic. Open all 10 on the topic page.