Programming Basics (Pseudocode Tracing)
The following program searches the n-element array a for the value x and stores the index where it is found in i. Array indices start at 1. and and or do not evaluate their right side when the left side alone decides the result. Which condition in 【a】 reads a[n + 1], outside the array, when x is not in a?
integer: i ← 1
while (【a】)
i ← i + 1
endwhile
- Aa[i] ≠ x and i ≦ n
- Bi ≦ n and a[i] ≠ x
- Cnot (i > n or a[i] = x)
Show answer and explanation
Answer: A. a[i] ≠ x and i ≦ n
If x is not in a, i grows to n + 1 and the condition is then tested. In i ≦ n and a[i] ≠ x, the left side i ≦ n is false, so a[i] on the right is not evaluated and nothing outside the array is read. In not (i > n or a[i] = x), the or is decided as soon as i > n is true, so a[i] is not evaluated either. a[i] ≠ x and i ≦ n evaluates a[n + 1] first. When relying on short-circuit evaluation, put the range check on the left.
- A. Correct. For i = n + 1 it evaluates a[n + 1] before checking the range.
- B. When the left side i ≦ n is false, the right side is not evaluated, so nothing outside the array is read.
- C. Once i > n is true the or is decided, so a[i] is not evaluated.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions