In this tutorial we will discuss, how to evaluate a postfix expression. Here, our assumption is that the numbers of the expression are single digited integers.
Algorithm for Postfix expression evaluation
1. Create a stack to store operands or values. 2. Scan the given postfix expression and do following for every scanned element. 3. If the element is a number, push it into the stack 4. If the element is a operator, pop operands for the operator from stack. Evaluate the operator and push the result back to the stack 5. When the expression is ended, the number in the stack is the final answer
Example
Let us take an expression
562+*84/-
and follow the algorithm. The steps are shown below.
Postfix Evaluation With Single Digit In C
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
#define SIZE 50
int top=-1;
void push(int *s,int item)
{
s[++top]=item;
}
int pop(int *s)
{
return(s[top--]);
}
int main()
{
char *pofx, ch;
int i = 0, op1, op2, *s;
pofx = (char *)malloc(sizeof(char)*SIZE);
s = (int *)malloc(sizeof(int)*SIZE);
printf("\n enter the postfix expression:");
scanf("%s", pofx);
while((ch = pofx[i++]) != '\0')
{
if(isdigit(ch))
push(s, ch-'0');
else
{
op2 = pop(s);
op1 = pop(s);
switch(ch)
{
case '+': push(s, (op1 + op2));
break;
case '-': push(s, (op1 - op2));
break;
case '*': push(s, (op1 * op2));
break;
case '/': push(s, (op1 / op2));
break;
case '^': push(s, pow(op1, op2));
break;
}
}
}
printf("\nresult after evaluation:%d\n", s[top]);
return 0;
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.