Count-Controlled Loops (FOR ... TO ... NEXT)

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

  1. Processing Arrays: Iterating from index 1 to Length(Array).
  2. Fixed-Size Data Sets: Entering grades for a known class of 30 students.
  3. Mathematical Progressions: Computing factorials, geometric progressions, or multiplication tables.

AI Socratic Tutor

All-Access
Sign in or create an account. AI Tutor is an All-Access benefit.
Sign Up

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.

Independent Practice: Factorial

+30 XP

Read an integer N from 0 to 8. Output N factorial. Remember that 0 factorial is 1.

Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.

solution.pseudo
All-Access Required

Interactive exercises for Module 2 and beyond require an active plan.

○ Empty product
○ One
○ Five
○ Eight