Consider the following program: #include <stdio.h> #include <stdlib.h>…

2007

Consider the following program:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define EOF -1

#define MAX_STACK_SIZE 100
int s[MAX_STACK_SIZE];
int top = -1;

void push(int value) { if (top < MAX_STACK_SIZE - 1) s[++top] = value; } /* push the argument on the stack */
int pop(void) { if (top == -1) return EOF; return s[top--]; }  /* pop the top of the stack */
void flagError() { fprintf(stderr, "Error!\n"); exit(1); }

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\n", 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

Attempted by 161 students.

Show answer & explanation

Correct answer: B

Solution: evaluate the postfix expression using a stack: push digits, and on an operator pop the top two values (first popped is the right operand), apply the operator, and push the result.

  • Token "5": push 5 → stack = [5]

  • Token "2": push 2 → stack = [5, 2]

  • Token "*": pop 2 and 5, compute 5 * 2 = 10, push 10 → stack = [10]

  • Token "3": push 3 → stack = [10, 3]

  • Token "3": push 3 → stack = [10, 3, 3]

  • Token "2": push 2 → stack = [10, 3, 3, 2]

  • Token "+": pop 2 and 3, compute 3 + 2 = 5, push 5 → stack = [10, 3, 5]

  • Token "*": pop 5 and 3, compute 3 * 5 = 15, push 15 → stack = [10, 15]

  • Token "+": pop 15 and 10, compute 10 + 15 = 25, push 25 → stack = [25]

Final result: the stack contains 25, so the program prints 25.

Explore the full course: Gate Guidance By Sanchit Sir