Unable to open this exercise
Common exam pitfall
Students often omit STEP -1 when counting backwards, resulting in a loop that never executes.
In algorithm design, iteration refers to repeating a block of instructions. When the exact number of iterations is known before entering the loop, developers use a Count-Controlled Loop (also called a FOR loop).
1. Cambridge Syntax
FOR <Counter> <- <StartValue> TO <EndValue>
// Statements executed on each iteration
NEXT <Counter>
Automatic Loop Counter Management:
- The loop counter is initialized to
<StartValue>. - At each
NEXT <Counter>, the runtime engine automatically increments<Counter>by 1 (or by<StepValue>if specified). - When
<Counter>exceeds<EndValue>, the loop terminates immediately and execution moves to the next statement. - Exam Rule: Do NOT manually increment the loop counter inside the loop body (e.g.
i <- i + 1), as this disrupts automatic step tracking!
2. Custom Steps and Decrementing
To increment by values other than 1, or to count backwards, use the STEP clause:
// Step by 2 (Odd numbers from 1 to 9):
FOR i <- 1 TO 9 STEP 2
OUTPUT i
NEXT i
// Counting backwards (Countdown from 10 to 1):
FOR Count <- 10 TO 1 STEP -1
OUTPUT Count
NEXT Count
3. Typical Use Cases for FOR Loops
- Processing Arrays: Iterating from index
1toLength(Array). - Fixed-Size Data Sets: Entering grades for a known class of 30 students.
- Mathematical Progressions: Computing factorials, geometric progressions, or multiplication tables.
AI Socratic Tutor
Need guidance? Ask a question or use the hint below.
AI Socratic Tutor is an All-Access Benefit
Unlock step-by-step Socratic hints, algorithm trace table walkthroughs, and error diagnostics for every Cambridge exercise.
You're chatting with an AI tutor, not a person. AI can make mistakes, so double-check its answers.
Exam-Style Question: Complete Decrementing FOR Loop Header
Complete the Cambridge pseudocode header and footer to count down from 10 down to 1:
FOR Count <- 10 [Space 1] 1 [Space 2] -1
OUTPUT Count
[Space 3] Count
Interactive exercises for Module 2 and beyond require an active plan.