For Loop CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
easyTrace: FOR i = 0 TO 4: OUTPUT i * i.
Solution
- 1 Step 1: i=0: output 0. i=1: output 1. i=2: output 4.
- 2 Step 2: i=3: output 9. i=4: output 16.
- 3 Step 3: Outputs: 0, 1, 4, 9, 16 (perfect squares).
Answer
0, 1, 4, 9, 16
FOR loops are used when the number of iterations is known in advance. The loop variable automatically increments each iteration.
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 โ