For Loop CS Thinking Example 3

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

Example 3

medium
Write a FOR loop that calculates 5!=5ร—4ร—3ร—2ร—15! = 5 \times 4 \times 3 \times 2 \times 1.

Solution

  1. 1
    Step 1: SET result = 1. FOR i = 1 TO 5: result = result * i.
  2. 2
    Step 2: Trace: 1*1=1, 1*2=2, 2*3=6, 6*4=24, 24*5=120.

Answer

120120. 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 โ†’

More For Loop Examples