ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (&& binds more tightly than ||, and both stop evaluating as soon as the result is known.)

What will be the output of the following pseudocode? (&& binds more tightly than ||, and both stop evaluating as soon as the result is known.)
Integer cnt = 0, hits = 0
Function chk(Integer v)
    cnt = cnt + 1
    return v > 2
End Function

for (each i from 1 to 5)
    if (chk(i) || chk(i - 1) && chk(i + 1))
        hits = hits + 1
    end if
end for
Print hits, cnt
  1. A. 3 10
  2. B. 3 7
  3. C. 3 9
  4. D. 2 7

Correct answer: B. 3 7

The condition is chk(i) || (chk(i − 1) && chk(i + 1)). i = 1: chk(1) false, chk(0) false, so chk(2) is skipped — 2 calls. i = 2: chk(2) false, chk(1) false — 2 calls. i = 3, 4, 5: chk(i) is true, so the right side is skipped — 1 call each. hits = 3, cnt = 2 + 2 + 3 = 7. '3 10' reads the condition left to right as (chk(i) || chk(i − 1)) && chk(i + 1).

More Pseudocode and Code Tracing questions

Exams that ask this topic