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]); 
}

 

 

Rabins Sharma Lamichhane

Rabins Sharma Lamichhane is the owner of RabinsXP who is constantly working for increasing Internet of Things (IoT) in Nepal. He also builds android apps and crafts beautiful websites. He is also working with various social services. The main aim of Lamichhane is to digitally empower the citizens of Nepal and make the world spiritually sound better both in terms of technology and personal development.

You may also like...

Leave a Reply

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

four − 1 =

%d bloggers like this: