ProgrammingHardTCS NQT · Accenture pattern

What will be the output? (&& does not evaluate its right side when the left side is false.)

What will be the output? (&& does not evaluate its right side when the left side is false.)
Integer c = 0, s = 0
Function inc()
    c = c + 1
    return c
End Function

for (each i from 1 to 5)
    if (i mod 2 == 0 && inc() > 1)
        s = s + i
    end if
end for
Print s, c
  1. A. 6 2
  2. B. 6 5
  3. C. 4 2
  4. D. 4 5

Correct answer: C. 4 2

inc() is called only when i is even (i = 2 and 4), so c ends at 2. At i = 2, inc() returns 1, which is not > 1. At i = 4 it returns 2, so s = 4. Assuming inc runs on every pass gives c = 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic