- Foundation
- About 13 min
- 5 practice questions
Repeating steps: loops
Trace for, while and do-while loops and calculate sums and counts they produce.
If something looks wrong, please tell us.
Computers are good at repeating. A loop runs the same steps many times, so a few lines can do thousands of operations.
Kinds of loops
| Loop | Behaviour | Condition checked |
|---|---|---|
| for | Repeats a known number of times | Before each pass |
| while | Repeats while a condition is true | Before each pass; may run zero times |
| do-while | Runs the body, then checks the condition | After each pass; runs at least once |
Parts of a loop
A loop needs a starting value, a condition to keep going and a change to the counter each time. If the counter never changes, the loop never ends: an infinite loop.
Tracing
Example 1. Sum of 1 to 5. total = 0; FOR i = 1 to 5: total = total + i. After each pass total is 1, 3, 6, 10, 15. The final result is 15.
Example 2. Factorial of 5. result = 1; FOR i = 1 to 5: result = result x i. Values: 1, 2, 6, 24, 120. Final 120.
Example 3. FOR i = 1 to 4 print i x 2. It prints 2, 4, 6, 8. The loop body runs 4 times.
Example 4. i = 10; WHILE i < 5 print i. The condition 10 < 5 is false at once, so the body runs 0 times. A do-while with the same body would print 10 once.
A loop needs a start, a condition and a change. while may run zero times; do-while runs at least once.
Key takeaways
- Loops repeat steps; for, while and do-while differ in when they check.
- Trace loops by tracking the variables after each pass.
Check your understanding
-
1. total = 0; FOR i = 1 to 6: total = total + i. What is the final total?
- 15
- 21
- 6
- 36
Show answer
Answer: B. total goes 1, 3, 6, 10, 15, 21. So the final total is 21.
-
2. result = 1; FOR i = 1 to 4: result = result x i. What is the final result?
- 10
- 24
- 4
- 16
Show answer
Answer: B. result goes 1, 2, 6, 24 (1 x 2 x 3 x 4), so it is 24.
-
3. i = 10; WHILE i < 5: print i. How many times does the body run?
- Once
- 0 times
- 5 times
- 10 times
Show answer
Answer: B. The condition 10 < 5 is false at the start, so a while loop does not run the body at all.
-
4. Which loop always runs its body at least once?
- for
- while
- do-while
- none of these loops
Show answer
Answer: C. A do-while runs the body first and checks the condition afterwards, so it always runs at least once.
-
5. A loop's counter is never changed, so its condition never becomes false. This is
- A syntax error in the flowchart
- A do-while loop
- A constant
- An infinite loop
Show answer
Answer: D. A loop needs a start, a condition and a change. Without a change the condition never becomes false and the loop never ends: an infinite loop.
Sign in to keep track of the lessons you finish.