While Loop CS Thinking Example 1

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

Example 1

medium
Trace: SET n = 1. WHILE n < 100: n = n * 2. OUTPUT n. How many iterations?

Solution

  1. 1
    Step 1: Start at n=1n = 1 and double each time: 1โ†’2โ†’4โ†’8โ†’16โ†’32โ†’64โ†’1281 \to 2 \to 4 \to 8 \to 16 \to 32 \to 64 \to 128.
  2. 2
    Step 2: After reaching 128128, the condition 128<100128 < 100 is false, so the loop stops.
  3. 3
    Step 3: The loop doubled nn seven times, so the output is 128128 after 77 iterations.

Answer

Output: 128. 7 iterations.
A WHILE loop repeats as long as its condition is true. The condition is checked before each iteration, so the loop may execute zero or more times.

About While Loop

A control structure that repeats a block of code as long as a specified condition remains true. The condition is checked before each iteration, and if it is false from the start, the loop body never executes at all.

Learn more about While Loop โ†’

More While Loop Examples