Iteration CS Thinking Example 1

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

Example 1

easy
Trace: FOR i = 1 TO 4: OUTPUT i * 2.

Solution

  1. 1
    Step 1: i = 1: output 2. i = 2: output 4.
  2. 2
    Step 2: i = 3: output 6. i = 4: output 8.
  3. 3
    Step 3: Loop ends after i = 4. Outputs: 2, 4, 6, 8.

Answer

2, 4, 6, 8
Iteration (looping) repeats a block of code a specified number of times. A FOR loop is used when we know in advance how many repetitions are needed.

About Iteration

Repeating a block of instructions multiple times until a stopping condition is satisfied. Iteration is one of the three fundamental control structures (along with sequence and selection) and is implemented through while loops, for loops, and other looping constructs.

Learn more about Iteration โ†’

More Iteration Examples