• 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

Loops
LoopBehaviourCondition checked
forRepeats a known number of timesBefore each pass
whileRepeats while a condition is trueBefore each pass; may run zero times
do-whileRuns the body, then checks the conditionAfter 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.

— Remember

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. 1. total = 0; FOR i = 1 to 6: total = total + i. What is the final total?

    1. 15
    2. 21
    3. 6
    4. 36
    Show answer

    Answer: B. total goes 1, 3, 6, 10, 15, 21. So the final total is 21.

  2. 2. result = 1; FOR i = 1 to 4: result = result x i. What is the final result?

    1. 10
    2. 24
    3. 4
    4. 16
    Show answer

    Answer: B. result goes 1, 2, 6, 24 (1 x 2 x 3 x 4), so it is 24.

  3. 3. i = 10; WHILE i < 5: print i. How many times does the body run?

    1. Once
    2. 0 times
    3. 5 times
    4. 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. 4. Which loop always runs its body at least once?

    1. for
    2. while
    3. do-while
    4. 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. 5. A loop's counter is never changed, so its condition never becomes false. This is

    1. A syntax error in the flowchart
    2. A do-while loop
    3. A constant
    4. 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.

Privacy · Terms · Refunds · Delivery