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
- A1
- B2
- 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.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions