Control Flow
Conditionals and loops; tracing code by hand.
Control flow is the order in which a program's statements run. By default, statements run top to bottom. Conditionals (`if`, `else if`, `else`) choose between branches based on a Boolean test, and loops (`for`, `while`) repeat a block until a condition changes.
Tracing code by hand, keeping a table of each variable's value after every step, is the most reliable way to predict what a program does and to find bugs. Most loop bugs are off-by-one errors at the boundaries or conditions that never become false, which create infinite loops.
Key ideas
- A `for` loop suits a known number of repetitions; a `while` loop suits repeat-until-done.
- Check boundary cases: zero iterations, one iteration and the last iteration.
- Combine conditions with and, or and not; watch operator precedence.
- Nested loops multiply: an outer loop of with an inner loop of runs times.
Worked example
What does this print? `total = 0; for i in 1..4: total = total + i * i; print(total)`
- : total .
- : total .
- : total .
- : total , which is printed.
Answer:
Common mistakes
- Off-by-one errors: using `<` where `<=` is needed or starting at 1 instead of 0.
- Forgetting to update the loop variable in a `while` loop.
- Using `=` (assignment) where `==` (comparison) is meant.
Practice questions
Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.
1.How many times does a loop from while , step 2, run?
Show answer
2.A loop adds for to . Final total?
Show answer
3.An outer loop runs 6 times and an inner loop 4 times per outer pass. How many inner executions?
Show answer