Loop Patterns
Loop Patterns
Most pseudocode output questions are loop-pattern questions.
FOR loop
FOR i = 1 TO 5
DISPLAY i
END FOR
Output:
1 2 3 4 5
If loop includes both ends, count is:
end - start + 1
FOR loop with step
FOR i = 2 TO 10 STEP 2
DISPLAY i
END FOR
Output:
2 4 6 8 10
Reverse loop
FOR i = 5 DOWNTO 1
DISPLAY i
END FOR
Output:
5 4 3 2 1
WHILE loop
Condition checked before loop body.
SET i = 1
WHILE i <= 3
DISPLAY i
SET i = i + 1
END WHILE
Output:
1 2 3
REPEAT UNTIL loop
Body executes first. Condition checked later.
SET i = 5
REPEAT
DISPLAY i
SET i = i + 1
UNTIL i > 5
Output:
5
Nested loop count
FOR i = 1 TO 3
FOR j = 1 TO 2
DISPLAY i, j
END FOR
END FOR
Inner loop runs 2 times for each i.
Total output lines:
3 × 2 = 6
Pattern printing
Triangle
FOR i = 1 TO 4
FOR j = 1 TO i
DISPLAY "*"
END FOR
DISPLAY newline
END FOR
Output:
*
**
***
****
Number of stars:
1 + 2 + 3 + 4 = 10
Common loop output patterns
| Pattern | Code idea | Output idea |
|---|---|---|
| Sum 1 to n | sum = sum + i |
n(n+1)/2 |
| Factorial | fact = fact * i |
n! |
| Count digits | divide by 10 | number of digits |
| Reverse number | rev = rev*10 + digit |
reversed digits |
| Multiplication table | n*i |
table values |
| Nested count | outer × inner | total iterations |
Off-by-one examples
FOR i = 1 TO 5
Runs 5 times.
WHILE i < 5
If i starts at 1, runs for i=1,2,3,4 = 4 times.
WHILE i <= 5
If i starts at 1, runs for i=1,2,3,4,5 = 5 times.