KTU S1

Repetition — the FOR Loop

By the end you should be able to: Write pseudocode using a FOR loop with ascending and descending counters, and explain when a FOR loop is the correct choice of loop.

Repetition executes a block of statements more than once. The FOR loop is the variant used when you know in advance how many times to repeat.

The form

FOR counter ← start TO end
    statements
ENDFOR

The counter is initialised to start, the body runs, the counter increases by one, and this continues while the counter has not passed end.

FOR i ← 1 TO 5
    PRINT i
ENDFOR

prints 1, 2, 3, 4, 5. Five iterations.

Counting downward

Add STEP -1:

FOR i ← 50 DOWNTO 1
    PRINT i
ENDFOR

or equivalently

FOR i ← 50 TO 1 STEP -1

Both are accepted conventions. Be consistent within one answer.

Counting how many iterations

For FOR i ← a TO b the body runs (b−a+1)(b - a + 1) times.

FOR i ← 1 TO 5 → 5−1+1=55 - 1 + 1 = 5 ✓ FOR i ← 0 TO 4 → 4−0+1=54 - 0 + 1 = 5 ✓ FOR i ← 3 TO 3 → 3−3+1=13 - 3 + 1 = 1 — runs once, not zero FOR i ← 5 TO 1 → 1−5+1=−31 - 5 + 1 = -3 → runs zero times

The +1 catches people out. Off-by-one errors are the commonest loop bug, and this formula is how you check.

When to use FOR

Use FOR when the iteration count is known before the loop starts:

  • Repeat exactly n times
  • Process every element of a list of known length
  • Count 1 to 50

Do not use FOR when the loop should stop on a condition discovered during execution — reading until the user types 0, or until a value is found. That's a WHILE loop.

Don't modify the counter inside the loop

FOR i ← 1 TO 10
    i ← i + 2        ← wrong
ENDFOR

The FOR loop manages its own counter. Changing it inside makes the iteration count unpredictable and is a defect in almost every case. If you need irregular stepping, use WHILE.

Accumulator pattern

The most common use of a counted loop: build up a total.

sum ← 0                      initialise BEFORE the loop
FOR i ← 1 TO n
    READ x
    sum ← sum + x
ENDFOR
PRINT sum

Two rules: initialise the accumulator before the loop (0 for sums, 1 for products), and update it inside. Initialising inside resets it every iteration — a classic error that leaves you with only the last value.