ProgrammingHardTCS NQT Advanced · Capgemini

What will be the output of the following pseudocode? (&& stops as soon as the left side is false)

What will be the output of the following pseudocode? (&& stops as soon as the left side is false)
Integer c = 0, k = 0
Function f(Integer x)
    c = c + 1
    return (x mod 3 == 0)
End Function
for (each i from 1 to 10)
    if (f(i) && f(i + 1))
        k = k + 1
    end if
end for
Print k, c
  1. A. 0 13
  2. B. 0 20
  3. C. 3 13
  4. D. 0 10

Correct answer: A. 0 13

&& short-circuits: f(i + 1) is called only when f(i) is true, i.e. for i = 3, 6, 9, and then 4, 7, 10 are not multiples of 3. So k stays 0 and c = 10 + 3, giving 0 13.

More Pseudocode and Code Tracing questions

Exams that ask this topic