For Loop CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

medium
Convert this FOR loop to a WHILE loop: FOR i = 1 TO 5: OUTPUT i.

Solution

  1. 1
    Step 1: Initialise: SET i = 1.
  2. 2
    Step 2: Condition: WHILE i <= 5.
  3. 3
    Step 3: Body + update: OUTPUT i. i = i + 1.

Answer

SET i = 1. WHILE i <= 5: OUTPUT i. i = i + 1.
Every FOR loop can be rewritten as a WHILE loop with explicit initialisation, condition, and update. FOR loops are syntactic sugar for this common pattern.

About For Loop

A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.

Learn more about For Loop โ†’

More For Loop Examples