in DS edited by
6,780 views
25 votes
25 votes

Consider the following C program: 

  #include <stdio.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);
                     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 \ + * +$

  1. $15$
  2. $25$
  3. $30$
  4. $150$
in DS edited by
6.8k views

4 Comments

because we take c as getchar() so it is character not int(c = getchar ())
1
1
if we do printf("% d", pop ()); then it will print ascii value of that character
0
0

isn’t stack will full with whole expression ? as , getchar assign the value in c variable which is an ascii value then every symbol will get push ? like * will get push as c variable contains * as 42 . so get pushed .. @Sachin Mittal 1 .

i think function isdigit() they should also defined for this question . 

0
0

2 Answers

31 votes
31 votes
Best answer

Correct Option: B

$25$
let first part
$5$ ----push
$2$------push
push------$5*2=10$. (pops $5$ and $2$)

push $3$
push $3$
push $2$
push $3+2 = 5$ (pops $2$ and $3$)
push $5*3 = 15$ (pops ($5$ and $3$)
push $15 + 10 = 25$ (pops ($15$ and $10$)

edited by

4 Comments

@ASNR1010 you are right brother , there’s mistake in the question.

1
1

@ASNR1010

i think %c is because of   

 while ((c = getchar ()) != EOF)

getchar  !! 

0
0
I think here first every character is converted to corresponding ASCII value due to int c, and at end the result is again converted to the character so %c. Is it correct?
0
0
3 votes
3 votes

It is equivalent to (5*2) + 3 * (3+2) = 10 + 3 *5 = 25

refer https://gateoverflow.in/8408/gate2015-3_12 this method 

edited by
Answer:

Related questions