Programming Basics (Pseudocode Tracing)
The following program was meant to compute the sum of all elements of array a. Array indices start at 1. What is the value of s after it runs?
integer array: a ← {4, 7, 1, 9, 3}
integer: s ← 0
for (i from 1 to length(a) − 1 step 1)
s ← s + a[i]
endfor
- A20
- B21
- C24
Show answer and explanation
Answer: B. 21
length(a) is 5, so i runs from 1 to 4 and s = 4 + 7 + 1 + 9 = 21. The last element a[5] = 3 is not added, so the result is 3 less than the correct sum 24. Carrying over the pattern for languages whose indices start at 0 (from 0 to length − 1) to arrays that start at 1 causes this kind of off-by-one error.
- A. This is a[2] to a[5]. i starts at 1, so a[1] = 4 is added and a[5] is not.
- B. Correct. a[1] to a[4]: 4 + 7 + 1 + 9 = 21.
- C. This is the sum of all elements, the intended value. The final value is length − 1, so a[5] is not added.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions