GATE IT 2007 · Arrays & Matrix Representation

MCQ · 1 mark · Problem PROG-DSTR-0193

Consider the following C program:
#include <stdio.h>
#include <ctype.h>
#define EOF -1
void push (int); /* push the argument on the stack */
int pop (void); /* pop the top of the stack */
void flagError ();
int main ()
{   int c, m, n, r;
    while ((c = getchar ()) != EOF)
    {   if (isdigit (c))
            push (c - '0');
        else if ((c == '+') || (c == '*'))
        {   m = pop ();
            n = pop ();
            r = (c == '+') ? n + m : n * m;
            push (r);
        }
        else if (c != ' ')
            flagError ();
    }
    printf("%d", pop ());
}
What is the output of the program for the following input?\(5\;\;2\;\;*\;\;3\;\;3\;\;2\;\;+\;\;*\;\;+\)
  1. A
    15
  2. B
    25
  3. C
    30
  4. D
    150

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

Show the worked solutionThe program evaluates a postfix expression with a stack: a digit is pushed as its value, and \(+\) or \(*\) pops two values and pushes the result.5 2 then \(*\): \(5\times2=10\). Stack: 10.3 3 2 then \(+\): \(3+2=5\). Stack: 10, 3, 5.Then \(*\): \(3\times5=15\). Stack: 10, 15.Then \(+\): \(10+15=25\).The output is 25. (The paper printed push(c) and "%c", which would push character codes; its key, 25, assumes the digit values are pushed, as in the code above.)Answer: B

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