You are on page 1of 2

6.

Write a C Program to evaluate a valid suffix/postfix expression


using stack. Assume that the suffix/postfix expression is read as
a single line consisting of non-negative single digit operands and
binary arithmetic operators. The arithmetic operators are +(add),
-(subtract), *(multiply) and /(divide).

PROGRAM

#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>

float cal(float op1,char ch,float op2)


{
switch(ch)
{
case '+': return (op1+op2);
case '-': return (op1-op2);
case '*': return (op1*op2);
case '/': return (op1/op2);
case '^': return (pow(op1,op2));
}
}

void main()
{
float s[100],res,op1,op2;
int i,top=-1;
char pos[100],sym;
clrscr();
printf("\nEnter the postfix expression..\n");
scanf("%s",pos);
for(i=0;i<strlen(pos);i++)
{
sym=pos[i];
if(isdigit(sym))
{
s[++top]=sym-'0';
}
else
{
op2=s[top--];
op1=s[top--];
res=cal(op1,sym,op2);
s[++top]=res;
}
}
res=s[top--];
printf("\n%s = %f",pos,res);
getch();
}

OUTPUT
Enter the postfix expression..
23^6*9-45/78+/+

23^6*9-45/78+/+ = 39.053333