C Program for Evaluation of Postfix Expression 34*5+

Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#define SIZE 50            /* Size of Stack */
#include <ctype.h>
int s[SIZE];
int top=-1;       /* Global declarations */
 
push(int elem)
{                       /* Function for PUSH operation */
    s[++top]=elem;
}
 
int pop()
{                      /* Function for POP operation */
    return(s[top--]);
}
 
main()
{                         /* Main Program */
    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;
            }
        }
    }
    printf("\n Given Postfix Expn: %s\n",pofx);
    printf("\n Result after Evaluation: %d\n",s[top]);
}

2 Responses to “C Program for Evaluation of Postfix Expression 34*5+”

    • #define SIZE 50
      #include /* Size of Stack */
      #include
      int s[SIZE];
      int top=-1; /* Global declarations */

      int push(int elem)
      { /* Function for PUSH operation */
      s[++top]=elem;
      }

      int pop()
      { /* Function for POP operation */
      return(s[top–]);
      }

      void main()
      { /* Main Program */
      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;
      }
      }
      }
      printf(“\n Given Postfix Expn: %s\n”,pofx);
      printf(“\n Result after Evaluation: %d\n”,s[top]);
      }

      Reply

Leave a Reply to Nitish

Click here to cancel reply.