While Loop CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumTrace: SET total = 0. SET i = 1. WHILE i <= 4: total = total + i. i = i + 1. OUTPUT total.
Solution
- 1 Step 1: i=1: total=0+1=1, i=2. i=2: total=1+2=3, i=3. i=3: total=3+3=6, i=4. i=4: total=6+4=10, i=5.
- 2 Step 2: i=5: 5 <= 4 is false, loop ends. Output: 10.
Answer
. Sum of 1+2+3+4.
This WHILE loop implements the accumulator pattern to sum consecutive integers. The loop variable i controls both the value added and when the loop terminates.
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 โ