GATE DA 2025 | Question 64
Consider the following pseudocode.
Create empty stack S
Set x=0, flag=0, sum=0
Push x onto S
while (S is not empty){
if (flag equals 0){
Set x = x+1
Push x onto S}
if (x equals 8):
Set flag=1
if (flag equals 1){
x = Pop(S)
if (x is odd):
Pop(S)
Set sum = sum + x}
}
Output sumThe value of sum output by a program executing the above pseudocode is ________ (Answer in integer)
Explanation
Answer: 24
While flag is 0, each pass pushes the next value, so the stack grows to 0, 1, …, 8 (top 8). In the pass that pushes 8, x equals 8, so flag becomes 1 (for good) and the third block already runs in that same pass.
Each such pass pops the top into x and adds it to sum; if x is odd, the element below it is popped and thrown away:
- pop 8 (even): sum = 8
- pop 7, discard 6: sum = 15
- pop 5, discard 4: sum = 20
- pop 3, discard 2: sum = 23
- pop 1, discard 0: sum = 24
The stack is now empty, so the loop stops and 24 is output.
Answer: 24