GATE DA 2025 · Stacks

NAT · 2 marks · Problem PROG-DSTR-0061

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)

Numerical answer (NAT).

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionInitially, \(x=0,\quad flag=0,\quad sum=0.\)Push 0 onto the stack.Stack (Bottom - Top): 0Since flag = 0, the program repeatedly increments x by 1 and pushes it onto the stack until x = 8.The stack becomes: Bottom - 0, 1, 2, 3, 4, 5, 6, 7, 8 - TopWhen x = 8, the second if statement sets \(flag=1.\)Since these are independent if statements, the third if statement is also executed in the same iteration.Now the stack operations are as follows:Iteration Value popped (x) x is Odd? Additional Pop() sum1 8 No — 82 7 Yes 6 153 5 Yes 4 204 3 Yes 2 235 1 Yes 0 24After the last iteration, the stack becomes empty, so the while loop terminates.Therefore, the final value of sum is 24.Correct Answer: 24Click Here for Detail SolutionGateOverflow discussion: https://gateoverflow.in/460968/gate-da-2025-question-54

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com