Open In App

GATE | Gate IT 2007 | Question 32

Last Updated : 28 Jun, 2021
Like Article
Like
Save
Share
Report

Consider the following C program:




   #include 
           #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);
                     else if ((c == '+') || (c == '*'))
                    {          m = pop ();
                                n = pop ();
                                r = (c == '+') ? n + m : n*m;
                                push (r);
                      }
                      else if (c != ' ')
                               flagError ();
             }
              printf("% c", pop ());
}


What is the output of the program for the following input ?
5 2 * 3 3 2 + * +
(A) 15
(B) 25
(C) 30
(D) 150


Answer: (B)

Explanation:  

The function of the program is:-

1) If the current character is a digit it pushes into stack
2) Else if the current character is operator,
  it pops two elements and then performs the operation.
Finally it pushes the resultant element into stack.
Initially stack s is empty. 5 2 * 3 3 2 + * +
1) 5 -> It pushes into s
2) 2 -> It pushes into s
3) * -> It pops two elements n = 2, m=5 n*m = 10 It pushes 10 into s
4) 3 -> It pushes into s
5) 3 -> It pushes into s
6) 2 -> It pushes into s
7) + -> n=2, m=3 n+m=5 It pushes 5 into s
8) * -> n=5, m=3 n*m=15 It pushes 15 into s
9) + -> n=15, m=10 n+m = 25 It pushes 25 into s.

 

Finally the result value is the only element present in stack.

This solution is contributed  by Anil Saikrishna Devarasetty.

Result = 25

Quiz of this Question



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads