The GATE Grind

GATE 2025 DA – Question 64

Programming, Data Structures and Algorithms · Stacks, queues, linked lists, trees and hash tables · 2 marks · Numerical answer

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*)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 24

Explanation

While the flag is 0, x goes from 1 to 8 and each value is pushed, so the stack holds 0, 1, 2, ..., 8. When x reaches 8 the flag becomes 1, and from then on every pass pops. The first pop gives 8, which is even, so nothing else is popped and sum becomes 8. The next pop gives 7, which is odd, so 6 is popped too, and sum becomes 15. The next pop gives 5, which is odd, so 4 is removed, and sum is 20. Then 3 is popped and 2 removed, sum is 23. Then 1 is popped and 0 removed, sum is 24, and the stack is empty. The output is 24.