10.2 Control Flow
Key Takeaways
- Control flow decides which statements run and how many times — branching with if/else and repetition with for/while
- An if/else chain evaluates conditions in order; at most one branch body runs for a mutually exclusive chain
- for loops usually pack init, condition, and update; while loops separate those pieces — both risk off-by-one errors
- break exits the innermost loop immediately; continue skips the rest of the current iteration and goes to the next check/update
- Tracing loops means recording the loop variable and any accumulators on every iteration until the condition fails
Once you can evaluate expressions, the next skill is control flow: deciding which lines execute and how often. Cyber Test items commonly show a short if ladder or a tiny loop and ask for a final counter, printed sequence, or boolean outcome. Treat every branch and every iteration as a checkpoint in your state table.
Branching: if / else
A conditional runs a block only when a boolean expression is true.
Language-agnostic pattern:
IF score >= 90 THEN
SET grade TO "A"
ELSE IF score >= 80 THEN
SET grade TO "B"
ELSE
SET grade TO "C_or_below"
END IF
Python flavor:
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C_or_below"
C++ flavor:
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
Tracing Rules for Branches
- Evaluate conditions top to bottom.
- On the first true condition, run that body, then skip the remaining
else if/elseparts of that chain. - If none are true, run
elsewhen present; otherwise do nothing.
Worked example: score = 80.
score >= 90? falsescore >= 80? true →gradebecomes"B"- The final
elsedoes not run
If the first condition had been score >= 80 alone without an else-if chain, a score of 95 would still get whatever that single true branch assigns — chain order and boundary values (>= vs >) are deliberate exam pressure points.
Nested if
An if inside another if means both conditions must succeed for the inner body to run. Draw boxes mentally: the inner box only exists when the outer box is entered.
IF user_ok THEN
IF pin_ok THEN
SET access TO "granted"
ELSE
SET access TO "bad_pin"
END IF
ELSE
SET access TO "unknown_user"
END IF
With user_ok = false, you never look at pin_ok; access is "unknown_user".
Loops: while and for
A loop repeats a body while a condition holds.
while
SET i TO 0
SET total TO 0
WHILE i < 3 DO
SET total TO total + i
SET i TO i + 1
END WHILE
Iteration table:
| Enter check | i | total (before body) | After body |
|---|---|---|---|
0 < 3 true | 0 | 0 | total=0, i=1 |
1 < 3 true | 1 | 0 | total=1, i=2 |
2 < 3 true | 2 | 1 | total=3, i=3 |
3 < 3 false | 3 | 3 | exit |
Final: i = 3, total = 3. Notice the loop ran for i values 0, 1, 2 — three times — because the condition was i < 3, not i <= 3.
for
A for loop packages initialization, condition, and update. Same logic as the while above:
Python:
total = 0
for i in range(3): # 0, 1, 2
total += i
C++:
int total = 0;
for (int i = 0; i < 3; i++) {
total += i;
}
range(3) and i < 3 starting at 0 are the usual "three iterations" pattern.
Off-by-One Errors — High-Yield Trap
An off-by-one error means the loop runs one time too many or too few, or an index hits one past the last valid slot.
| Intent | Common correct pattern | Easy mistake |
|---|---|---|
| Run exactly n times with i = 0..n-1 | i < n | i <= n (runs n+1 times) |
| Include endpoints a..b inclusive | i <= b or range(a, b+1) | i < b drops b |
| Process array length n | indices 0 .. n-1 | using n as an index |
Worked trap: "Sum integers from 1 through 5."
Correct while:
SET s TO 0
SET i TO 1
WHILE i <= 5 DO
SET s TO s + i
SET i TO i + 1
END WHILE
Result s = 15. If the condition were i < 5, you would only add 1+2+3+4 = 10 — a classic wrong answer planted beside 15 on multiple-choice exams.
Another trap: counting down.
SET n TO 3
WHILE n > 0 DO
SET n TO n - 1
END WHILE
Final n is 0. If the body decremented after a different check, or used >= 0, you might land on -1. Always ask: last value that still entered the loop, and value after the last update.
break and continue
| Keyword | Effect |
|---|---|
break | Leave the innermost loop immediately; skip remaining iterations |
continue | Skip the rest of this iteration; go to the next condition/update |
break example:
SET i TO 0
SET found TO -1
WHILE i < 10 DO
IF i == 4 THEN
SET found TO i
BREAK
END IF
SET i TO i + 1
END WHILE
When i becomes 4, found is set to 4 and the loop ends. Without break, the loop would keep going to 10.
continue example (C++-style counting of odds):
int count = 0;
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) continue;
count++;
}
For i = 0,2,4 the continue skips count++. Odds 1 and 3 increment → count = 2.
Python equivalent idea:
count = 0
for i in range(5):
if i % 2 == 0:
continue
count += 1
Same result. Exam stems may ask whether a statement after continue runs on that iteration — it does not.
Nested Loops (Brief)
An outer loop with an inner loop multiplies iterations: if outer runs 3 times and inner runs 4 times each, the inner body runs 12 times. Trace with a pair (outer, inner) in your table. A break only breaks the inner loop unless the language offers a labeled break (rarely tested at this level).
SET hits TO 0
FOR i FROM 0 TO 1 DO # i = 0, 1
FOR j FROM 0 TO 2 DO # j = 0, 1, 2
SET hits TO hits + 1
END FOR
END FOR
hits ends at 6.
Combined Worked Trace
SET n TO 0
FOR k FROM 1 TO 5 DO
IF k % 2 == 0 THEN
CONTINUE
END IF
SET n TO n + k
IF n > 6 THEN
BREAK
END IF
END FOR
Assume FOR k FROM 1 TO 5 means k = 1,2,3,4,5.
| k | even? | action | n |
|---|---|---|---|
| 1 | no | n = 0+1 = 1; 1 > 6? no | 1 |
| 2 | yes | continue | 1 |
| 3 | no | n = 4; 4 > 6? no | 4 |
| 4 | yes | continue | 4 |
| 5 | no | n = 9; 9 > 6? yes → break | 9 |
Final n = 9. If you forget continue on evens, you would add 2 and 4 as well and hit the break earlier with a different sum — exact tracing beats intuition.
Exam Habits
- For every loop, list the sequence of loop-variable values that actually enter the body.
- Boundary words matter: "through 5," "less than 5," "up to but not including."
- On
if/else if, stop at the first match. breakvscontinue: exit entirely vs skip to next iteration.- Assignment vs equality still appears inside conditions — do not let loop syntax distract you from
=vs==.
Control flow sets up functions: a function body is just statements with branches and loops, entered by a call and left by a return — the topic of the next section.
What is the final value of total after: total = 0; i = 1; while i < 4: total = total + i; i = i + 1?
In a for-loop over i = 0,1,2,3, a continue when i == 2 skips which action?
Code: x = 5; if x > 10: y = 1; else if x > 3: y = 2; else: y = 3. What is y?
How many times does the inner body run? for a in 0,1: for b in 0,1,2: body