Programming Basics (Pseudocode Tracing)
Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?
integer array: a ← {2, 2, 3, 3, 3, 1, 1}
integer: c ← 0
for (i from 1 to length(a) − 1 step 1)
if (a[i] = a[i + 1])
c ← c + 1
endif
endfor
- A4
- B6
- C7
Show answer and explanation
Answer: A. 4
The program counts pairs of adjacent elements that are equal. i runs from 1 to 6, and four pairs are equal: a[1] and a[2], a[3] and a[4], a[4] and a[5], and a[6] and a[7], so c = 4. There are 7 − 1 = 6 comparisons. The final value is length − 1 so that a[i + 1] stays within the array.
- A. Correct. The equal pairs are (2, 2), (3, 3), (3, 3) and (1, 1).
- B. This is the number of comparisons. c increases only for equal pairs.
- C. This is the number of elements that equal a neighbor. The program counts adjacent pairs, not elements.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions