Sunday, 30 October 2011

EVALUATION OF POSTFIX EXPRESSION


#include<stdio.h>
#include<ctype.h>
main()
{
char suffix[20];
float eval(char *);
clrscr();
printf("\nenter a valid postfix expression:-\n");
gets(suffix);
printf("\nresult of evaluation=%f\n",eval(suffix));
getch();
}
float eval(char *suffix)
{
float stack[20],x1,x2;
int i=0,top=-1;
char ch;
while((ch=suffix[i++])!='\0')
{
if(isdigit(ch))
stack[++top]=ch-'0';
else
{
x2=stack[top--];
x1=stack[top--];
switch(ch)
{
case '+':stack[++top]=x1+x2;
break;
case '-':stack[++top]=x1-x2;
break;
case '*':stack[++top]=x1*x2;
break;
case '/':stack[++top]=x1/x2;
break;
}
     }
   }
  return(stack[top]);
 }

No comments:

Post a Comment