Evaluation of Postfix Expression in C [Algorithm and Program]

Here you will get algorithm and program for evolution of postfix expression in C.

In postfix or reverse polish notation, every operator follows all of its operands.

For example: 5 3 2 * +

Also Read: Infix to Postfix Conversion in C [Program and Algorithm]

 

Algorithm for Evaluation of Postfix Expression

Create an empty stack and start scanning the postfix expression from left to right. 

  • If the element is an operand, push it into the stack.
  • If the element is an operator O, pop twice and get A and B respectively. Calculate BOA and push it back to the stack.
  • When the expression is ended, the value in the stack is the final answer.

Evaluation of a postfix expression using a stack is explained in below example:

Evaluation of Postfix Expression in C [Algorithm & Program]

 

Program for Evaluation of Postfix Expression in C

 

Output

Enter the expression(eg: 59+3*)
Single digit operand and operators only:74+5-

Value of expression=6

 

Image Credit: http://cis.stvincent.edu/html/tutorials/swd/stacks/stacks.html

5 thoughts on “Evaluation of Postfix Expression in C [Algorithm and Program]

  1. Ankita

    can you write a program for infix to postfix transformation and its evaluation in one program

    Reply
    1. giridhar

      #include
      #include
      #include

      #define SIZE 40

      int pop();
      void push(int);

      char postfix[SIZE];
      int stack[SIZE], top = -1;

      int main()
      {
      int i, a, b, result, pEval;
      char ch;

      for(i=0; i<SIZE; i++)
      {
      stack[i] = -1;
      }
      printf("\nEnter a postfix expression: ");
      scanf("%s",postfix);

      for(i=0; postfix[i] != '\0'; i++)
      {
      ch = postfix[i];

      if(isdigit(ch))
      {
      push(ch-'0');
      }
      else if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
      {
      b = pop();
      a = pop();

      switch(ch)
      {
      case '+': result = a+b;
      break;
      case '-': result = a-b;
      break;
      case '*': result = a*b;
      break;
      case '/': result = a/b;
      break;
      }

      push(result);
      }

      }

      pEval = pop();

      printf("\nThe postfix evaluation is: %d\n",pEval);

      return 0;
      }

      void push(int n)
      {
      if (top -1)
      {
      n = stack[top];
      stack[top–] = -1;
      return n;
      }
      else
      {
      printf(“Stack is empty!\n”);
      exit(-1);
      }
      }

      Reply
  2. Shankhabrata Das

    Can you do this with more than one digit???then pls do…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *