Programming Basics (Pseudocode Tracing)

In the following program, and does not evaluate its right side when the left side is false (short-circuit evaluation). cnt is a global variable. What is the value of cnt after the program runs?

integer: cnt ← 0
○boolean: even(integer: k)
  cnt ← cnt + 1
  return k mod 2 = 0
for (i from 1 to 5 step 1)
  if (i > 3 and even(i))
    output i
  endif
endfor
  1. A1
  2. B2
  3. C5
Show answer and explanation

Answer: B. 2

For i = 1 to 3 the left side i > 3 is false, so even(i) on the right is not called. For i = 4 and i = 5, i > 3 is true, so even(i) is called and cnt becomes 2. Only i = 4, for which the whole condition is true, is output. If both sides were always evaluated, even would be called 5 times and cnt would be 5.

  • A. This is the number of outputs, where the whole condition is true (once, for i = 4).
  • B. Correct. even is called only for i = 4 and 5.
  • C. This is the value without short-circuit evaluation, calling even every time.
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. 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?
  2. 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?
  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. What is the value of x after the following program runs?
  4. 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?
  5. 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?