Gradient LabSign up free

Home / GATE DA / 2025 / Q.64

GATE DA 2025, Q.64: Sum produced by a push-then-pop loop

Data structures and algorithmsStack simulation2 marksNumerical answerFree

The question

Start with an empty stack S, x = 0, flag = 0, sum = 0, and push x. While S is not empty: if flag = 0, set x = x + 1 and push x; if x = 8, set flag = 1; if flag = 1, pop into x, and if x is odd pop once more (discard), then add x to sum. What is the output sum?

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

Watch it solved

Solve it step by step

  1. Fill phase. Pushes 1 to 8 on top of 0: stack 0..8, then flag = 1.
  2. Pop 8. 8 is even: sum = 8.
  3. Pop 7. Odd, so 6 is discarded: sum = 15.
  4. Continue. Pop 5 (discard 4): 20. Pop 3 (discard 2): 23. Pop 1 (discard 0): 24. Stack empty.

Answer: 24

Official IIT Roorkee answer key: 24.

Common mistake. Adding the discarded even numbers too, which gives 36.

Remember. Simulate a stack step by step and write its contents after every pop.

Want every question solved? The past-paper pack has all 195 questions from 2024, 2025 and 2026 for ₹499. The cheat sheet pack has 23 printable sheets for ₹399.

See the past-paper pack See the cheat sheets

Source: official GATE DA 2025 question paper and answer key (IIT Roorkee). The question is lightly reworded; every number and option is kept.