ProgrammingVery hardAccenture · TCS · Infosys
This function uses a counter that PERSISTS across calls (a static/global variable), starting at 3. What does each of the 7 calls print, in order?
This function uses a counter that PERSISTS across calls (a static/global variable), starting at 3. What does each of the 7 calls print, in order?
Integer counter = 3 // static: keeps its value between calls
Function next()
counter = counter * 2 + 1
Print counter
end Function
// next() is called 7 times in a row- A. 6, 14, 30, 62, 126, 254, 510
- B. 7, 7, 7, 7, 7, 7, 7
- C. 7, 15, 31, 63, 127, 255, 511
- D. 511, 255, 127, 63, 31, 15, 7
Correct answer: C. 7, 15, 31, 63, 127, 255, 511
Because counter is static, each call updates the SAME variable left over from the previous call, not a fresh copy reset to 3. Tracing counter = 3 through 7 updates of counter = counter*2+1 gives, in order, 7, 15, 31, 63, 127, 255, 511. Resetting to 3 every call would wrongly give 7, 7, 7, 7, 7, 7, 7 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? 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 = 1958, c = 0 while (n > 0) c = c +…
- What will be the output of the following pseudocode? (One pass = one full sweep of the outer loop; indexed from 0.) Integer arr[6] = {89…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed…
- What is the final content of the stack (bottom to top, left to right) after this sequence of operations on an initially empty stack? push…