For Loop CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumWrite a FOR loop that calculates .
Solution
- 1 Step 1: SET result = 1. FOR i = 1 TO 5: result = result * i.
- 2 Step 2: Trace: 1*1=1, 1*2=2, 2*3=6, 6*4=24, 24*5=120.
Answer
. SET result = 1. FOR i = 1 TO 5: result = result * i.
The accumulator pattern works for products too โ initialise to 1 (the multiplicative identity) and multiply each value in the loop.
About For Loop
A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
Learn more about For Loop โ