Iteration CS Thinking Example 2

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

Example 2

medium
Trace: SET count = 0. SET n = 1. WHILE n <= 10: IF n MOD 2 == 0 THEN count = count + 1. n = n + 1. OUTPUT count.

Solution

  1. 1
    Step 1: The loop runs for n = 1, 2, 3, ..., 10.
  2. 2
    Step 2: n MOD 2 == 0 is true for n = 2, 4, 6, 8, 10 โ€” that is 5 even numbers.
  3. 3
    Step 3: count = 5. Output: 5.

Answer

55
This algorithm counts even numbers from 1 to 10. The WHILE loop continues as long as the condition is true, and the IF inside filters for even numbers using the modulo operator.

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