ProgrammingHardTCS NQT · Accenture pattern

This function uses a counter that PERSISTS across calls (a static/global variable), starting at 4. What does each of the 4 calls print, in order?

This function uses a counter that PERSISTS across calls (a static/global variable), starting at 4. What does each of the 4 calls print, in order?
Integer counter = 4  // static: keeps its value between calls
Function next()
    counter = counter * 2 + 1
    Print counter
end Function

// next() is called 4 times in a row
  1. A. 79, 39, 19, 9
  2. B. 9, 9, 9, 9
  3. C. 9, 19, 39, 79
  4. D. 8, 18, 38, 78

Correct answer: C. 9, 19, 39, 79

Because counter is static, each call updates the SAME variable left over from the previous call, not a fresh copy reset to 4. Tracing counter = 4 through 4 updates of counter = counter*2+1 gives, in order, 9, 19, 39, 79. Resetting to 4 every call would wrongly give 9, 9, 9, 9 every time.

More Pseudocode and Code Tracing questions

Exams that ask this topic