Loading ...

Postfix Evaluation in C

 

/* Evaluating postfix */
#include <stdio.h>
#include <math.h>
#define SIZE 50            /* Size of Stack */
#include <ctype.h>
int s[SIZE]; int top=-1;       /* Global declarations */
push(int elem) { s[++top]=elem; }
int pop() {  return(s[top--]); }

main()
{
  char pofx[50],ch;
  int i=0,op1,op2;
  printf("\n\nRead the Postfix Expression ? ");
  scanf("%s",pofx);
  while( (ch=pofx[i++]) != '\0')
  {
    if(isdigit(ch)) push(ch-'0'); /* Push the operand */
    else
      {        /* Operator,pop two  operands */
	op2=pop();    op1=pop();
        switch(ch)
         {
            case '+':push(op1+op2);break;
            case '-':push(op1-op2);break;
            case '*':push(op1*op2);break;
	    case '/':push(op1/op2);break;
	    case '%':push(op1%op2);break;
	    case '^':push(pow(op1,op2));break;
	    default : printf("Invalid operator\n");
         }   
      }  
  }  
  printf("\n Given Postfix Expn: %s\n",pofx);  
  printf("\n Result after Evaluation: %d\n",s[top]); 
}

 

 

Leave a Reply

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