ProgrammingVery hardCapgemini · Infosys pattern
This function uses a counter that PERSISTS across calls (a static/global variable), starting at 2. What does each of the 5 calls print, in order?
This function uses a counter that PERSISTS across calls (a static/global variable), starting at 2. What does each of the 5 calls print, in order?
Integer counter = 2 // static: keeps its value between calls
Function next()
counter = counter * 2 + 1
Print counter
end Function
// next() is called 5 times in a row- A. 5, 11, 23, 47, 95
- B. 95, 47, 23, 11, 5
- C. 4, 10, 22, 46, 94
- D. 5, 5, 5, 5, 5
Correct answer: A. 5, 11, 23, 47, 95
Because counter is static, each call updates the SAME variable left over from the previous call, not a fresh copy reset to 2. Tracing counter = 2 through 5 updates of counter = counter*2+1 gives, in order, 5, 11, 23, 47, 95. Resetting to 2 every call would wrongly give 5, 5, 5, 5, 5 every time.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Function isEven(Integer n) if (n == 0) return true end if return isOdd(n - 1) end…
- What will be the output of the following pseudocode? Function isEven(Integer n) if (n == 0) return true end if return isOdd(n - 1) end…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Function f(Integer n, Integer…
- What will be the output of the following pseudocode? Integer c = 0 for (each i from 1 to 12) for (each j from i + 1 to 12) if ((i + j) mod…
- What will be the output of the following pseudocode? (& is bitwise AND, >> is right shift.) Integer n = 841, c = 0 while (n > 0) c = c +…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed…