Iteration CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
easyTrace: FOR i = 1 TO 4: OUTPUT i * 2.
Solution
- 1 Step 1: i = 1: output 2. i = 2: output 4.
- 2 Step 2: i = 3: output 6. i = 4: output 8.
- 3 Step 3: Loop ends after i = 4. Outputs: 2, 4, 6, 8.
Answer
2, 4, 6, 8
Iteration (looping) repeats a block of code a specified number of times. A FOR loop is used when we know in advance how many repetitions are needed.
About Iteration
Repeating a block of instructions multiple times until a stopping condition is satisfied. Iteration is one of the three fundamental control structures (along with sequence and selection) and is implemented through while loops, for loops, and other looping constructs.
Learn more about Iteration โMore Iteration Examples
Example 2 medium
Trace: SET count = 0. SET n = 1. WHILE n <= 10: IF n MOD 2 == 0 THEN count = count + 1. n = n + 1. O
Example 3 easyWrite pseudocode using a loop to output the numbers 5, 10, 15, 20, 25.
Example 4 easyTrace this loop: SET total = 2. REPEAT 4 TIMES: SET total = total + 3. OUTPUT total.