Advertisement
Rakibul_Ahasan

Evaluation of Postfix Expression

Aug 27th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1.  #include<stdio.h>
  2.  #include<ctype.h>
  3.  
  4.  # define MAXSTACK 100
  5.  # define POSTFIXSIZE 100
  6.  
  7.  int stack[MAXSTACK];
  8.  int top = -1 ;  
  9.  
  10.  void push(int item)
  11.  {
  12.      if(top >= MAXSTACK -1)
  13.      {
  14.          printf("stack over flow");
  15.          return;
  16.      }
  17.      else
  18.      {
  19.          top = top + 1 ;
  20.          stack[top]= item;
  21.      }
  22.  }
  23.  
  24.  int pop()
  25.  {
  26.      int item;
  27.      if(top <0)
  28.      {
  29.         printf("stack under flow");
  30.      }
  31.      else
  32.      {
  33.          item = stack[top];
  34.          top = top - 1;
  35.          return item;
  36.      }
  37.  }
  38.  
  39.  void EvalPostfix(char postfix[])
  40.  {
  41.     int i ;
  42.     char ch;
  43.     int val;
  44.     int A, B ;
  45.  
  46.     for (i = 0 ; postfix[i] != ')'; i++){
  47.  
  48.         ch = postfix[i];
  49.         if (isdigit(ch))
  50.         {
  51.             push(ch - '0');
  52.         }
  53.         else if (ch == '+' || ch == '-' || ch == '*' || ch == '/'){
  54.             A = pop();
  55.             B = pop();
  56.  
  57.             switch (ch) /* ch is an operator */
  58.             {
  59.                 case '*':
  60.                 val = B * A;
  61.                 break;
  62.  
  63.                 case '/':
  64.                 val = B / A;
  65.                 break;
  66.  
  67.                 case '+':
  68.                 val = B + A;
  69.                 break;
  70.  
  71.                 case '-':
  72.                 val = B - A;
  73.                 break;
  74.             }
  75.             push(val);
  76.         }
  77.     }
  78.     printf( " \n Result of expression evaluation : %d \n", pop()) ;
  79.  }
  80.  
  81.  int main()
  82.  {
  83.     int i ;
  84.     char postfix[POSTFIXSIZE];
  85.  
  86.     for (i = 0 ; i <= POSTFIXSIZE - 1 ; i++){
  87.  
  88.         scanf("%c", &postfix[i]);
  89.  
  90.         if ( postfix[i] == ')' )
  91.         { break; }
  92.     }
  93.     EvalPostfix(postfix);
  94.  
  95.     return 0;
  96.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement