Monday 22 February 2016

Postfix expression evaluation

Postfix Evaluation

Algorithm:
  1. Create an empty stack and scan the postfix expression. 
  2. If the element is an operand, push it to the stack.
  3. If the element is an operator pop twice and suppose we get A and B respectively, then calculate B op A and push it to the stack.
  4. Repeat step 2 and 3 until the end of the expression. 
  5. Top of the stack contains the evaluated value.

Note: This program considers the basic operators: +, -, /, * and assumes the operand to be single digit.

Here is the C program for posftix expression evaluation:


#include<stdio.h>
#include<conio.h>
#include<string.h>
int top=0;
int stack[]={0};
void operate(char );

void main(){
      int i,l;
      char *postfix;
      clrscr();
      printf("Enter the postfix expression to be evaluated:\n");
       scanf("%s",postfix);
      l=strlen(postfix);
      for(i=0;i<l;i++){
      if(postfix[i]>=48 && postfix[i]<=57){
       stack[top++]=postfix[i]-48;  //push
      }
      else{
    operate(postfix[i]);
      }
      }
      printf("the value is: %d",stack[top-1]);
   getch();
}

void operate(char c){
     int val;
  if(c=='+'){
   val=stack[top-2]+stack[top-1];
   stack[top-2]=val;
   stack[top-1]=0;  
   top--;
  }
  else if(c=='-'){
   val=stack[top-2]-stack[top-1];
   stack[top-2]=val;
   stack[top-1]=0;  
   top--;
  }
  else if(c=='/'){
   val=stack[top-2]/stack[top-1];
   stack[top-2]=val;
   stack[top-1]=0;  
   top--;

     }
     else if(c=='*'){
       val=stack[top-2]*stack[top-1];
   stack[top-2]=val;
   stack[top-1]=0;  
   top--;
     }
}

No comments:

Post a Comment