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
  1. Aa[i] ≠ x and i ≦ n
  2. Bi ≦ n and a[i] ≠ x
  3. 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.
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. Real values are represented in IEEE 754 double precision (binary64), and each sum is rounded to the nearest representable value. What is the value of c after the following program runs?
  2. Class Counter gives each instance its own integer member variable count (0 when created), and its method inc() adds 1 to its own count. What is the value of x after the following program runs?
  3. Class Counter gives each instance its own integer member variable count (0 when created), and its method inc() adds 1 to its own count. A variable of type Counter holds a reference to an instance, not the instance itself. What is the value of x after the following program runs?
  4. The two assignments in the following program were meant to swap the values of x and y. What are the values of x and y after it runs?
  5. The following program passes values along three variables. What are the values of a, b and c after it runs?