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
  1. A20
  2. B21
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. Array indices start at 1. The following program looks for the largest element. What is the value of m after it runs?
  2. The following program was meant to reverse the elements of array a. Array indices start at 1. What does a contain after it runs?
  3. Array indices start at 1. What does array a contain after the following program runs?
  4. Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?
  5. m[i, j] is the element in row i, column j of the 2D array m, and indices start at 1. What is the value of s after the following program runs?