Programming Basics (Pseudocode Tracing)
The following for loop increases its control variable by 5. What is the value of c after it runs?
integer: c ← 0
for (i from 10 to 50 step 5)
c ← c + 1
endfor
- A8
- B9
- C10
Show answer and explanation
Answer: B. 9
i takes the values 10, 15, 20, 25, 30, 35, 40, 45 and 50; the next value 55 exceeds the final value 50, so the loop ends. (50 − 10) ÷ 5 = 8 is the number of intervals between them, and the number of values including both ends, 10 and 50, is 8 + 1 = 9, so the body runs 9 times. As with fence posts, confusing the number of intervals with the number of points causes an off-by-one error.
- A. This is the number of intervals, (50 − 10) ÷ 5 = 8, and misses the pass for i = 10.
- B. Correct. The body runs for the nine values from 10 to 50 in steps of 5.
- C. This is 50 ÷ 5 = 10, the count if i started at 5.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions