Programming Basics (Pseudocode Tracing)
The following for loop increases i by 2. What is the value of s after it runs?
integer: s ← 0
for (i from 1 to 10 step 2)
s ← s + i
endfor
- A25
- B30
- C36
Show answer and explanation
Answer: A. 25
i takes the values 1, 3, 5, 7 and 9; the next value 11 exceeds the final value 10, so the loop ends. s = 1 + 3 + 5 + 7 + 9 = 25. A for loop exits as soon as the control variable exceeds the final value, so the body never runs with a value beyond it.
- A. Correct. 1 + 3 + 5 + 7 + 9 = 25.
- B. This starts at 2: 2 + 4 + 6 + 8 + 10. The initial value is 1.
- C. This adds 11 as well. 11 exceeds the final value 10, so it is not used.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions