While Loop CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumTrace this code and state the final output:
SET n = 1
SET result = 1
WHILE n < 5
SET n = n + 1
SET result = result * n
END WHILE
OUTPUT result
Solution
- 1 Step 1: n=1, result=1. Check n < 5 โ TRUE. n becomes 2, result = 1 ร 2 = 2.
- 2 Step 2: n=2. Check n < 5 โ TRUE. n becomes 3, result = 2 ร 3 = 6.
- 3 Step 3: n=3. Check n < 5 โ TRUE. n becomes 4, result = 6 ร 4 = 24.
- 4 Step 4: n=4. Check n < 5 โ TRUE. n becomes 5, result = 24 ร 5 = 120.
- 5 Step 5: n=5. Check n < 5 โ FALSE. Loop ends.
Answer
120. The loop computes 5! (5 factorial = 1 ร 2 ร 3 ร 4 ร 5). Note that n is incremented before multiplying, so the multiplication starts at 2.
WHILE loops test the condition before each iteration. This example shows the accumulator pattern (result *= n) combined with a counter, producing a factorial calculation.
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 โ