IAE Academy

GATE 2025 DA Q.64: solution and answer

GATE 2025 · DAQ.64 · 2 marks · NAT

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 sum

The value of sum output by a program executing the above pseudocode is ______________ (Answer in integer)

See the question in the paper

Answer and solution

ANSWER

The program outputs .

Official answer: 24Source: Official answer key, GATE 2025 DA (IIT Roorkee)

  1. Initially the stack is (bottom to top), with , , .

  2. While , each pass of the loop executes x = x+1 and pushes the new . Nothing is popped. After pass 8, and . The test x equals 8 is now true, so flag=1.

  3. In that same pass 8 the flag equals 1 block also runs. x = Pop(S) gives and . Since 8 is even there is no second pop, and .

  4. From pass 9 on, , so the first if never runs again and nothing is pushed. The test x equals 8 may set flag=1 again, which changes nothing. Each pass pops once into , and pops a second element (discarded) if that is odd. The popped is the value added to sum.

  5. Pass 9: pop 7 (odd), so also pop 6. , .

  6. Pass 10: pop 5 (odd), so also pop 4. , .

  7. Pass 11: pop 3 (odd), so also pop 2. , .

  8. Pass 12: pop 1 (odd), so also pop 0. , and is empty, so the loop ends.

  9. Output: .

KEY IDEA

Split the run into two phases. First, with , the stack fills with . Then with , each pass pops one element and also discards the next one whenever the popped value is odd. Note that the pass in which reaches 8 also performs the first pop, because the flag equals 1 test comes after flag is set in the same pass.

WATCH OUT FOR

Treating the pass that sets flag=1 as a pure push pass and so skipping the pop of 8. That leaves 8 out of the sum and gives 16 instead of 24. Another slip is to forget that the second pop after an odd value discards the next element without adding it to the sum.

From the GATE 2025 DA paper. Every question of this paper · Download the full paper · All 13 Linear structures questions, with notes

More Linear structures questions