Google Search

Sunday, January 29, 2012

C PROGRAM TO EVALUATE POSTFIX EXPRESSION


ALGORITHM TO EVALUATE POSTFIX EXPRESSION


P   postfix expression
1.  Add a right parenthesis “)” at the end of P
2.  Scan P from left to right and repeat steps 3 & 4 until sentinel “)” is 
     encountered
3.  If an operand is encountered, put it on stack
4.  If an operator      is encountered , then:
     a)  Remove the top two elements of stack , where A is the top element 
          & B is the next to top element
    b)  Evaluate B    A
    c)  Place the result of (b) back on stack
5.  Set value equal to the top element on stack
6.  Exit



  //evaluation of postfix expression//


#include<stdio.h>
#include<conio.h>
float stack[10];
int top=-1;
void push(char);
float pop();
float eval(char [],float[]);
void main()
{
int i=0;
char suffix[20];
float value[20],result;
clrscr();
printf("Enter a valid postfix expression\t");
gets(suffix);
while (suffix[i]!='\0')
{
if(isalpha(suffix[i]))
{
fflush(stdin);
printf("\nEnter the value of %c",suffix[i]);
scanf("%f",&value[i]);
}
i++;
}
result=eval(suffix,value);
printf("The result of %s=%f",suffix,result);
getch();
}


float eval(char suffix[],float data[])
{
int i=0;
float op1,op2,res;
char ch;
while(suffix[i]!='\0')
{
ch=suffix[i];
if(isalpha(suffix[i]))
{
push(data[i]);
}
else
{
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(pow(op1,op2));
break;
}
}
i++;
}
res=pop();
return(res);
}
void push(char num)
{
top=top+1;
stack[top]=num;
}
float pop()
{
float num;
num=stack[top];
top=top-1;
return(num);

1 comments:

Dev said...

ERROR:
case '*' : push(op1+op2);
CORRECTION:
case '*' : push(op1*op2);

Post a Comment