Write a program to evaluate a postfix expression using stacks.

#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
class test
{
stack<int> s;
char exp[20];
int len,a,b,res,op=0;
public:
void getdata()
{
cout<<"Enter the Expression( e.g. 24 56 + ) : ";
gets(exp);
len=strlen(exp);
}
bool opr(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
return true;
else
return false;
}
void result(int a,int b,char ch)
{
switch(ch)
{
case '+':res=a+b;
break;
case '-':res=a-b;
break;
case '*':res=a*b;
break;
case '/':res=a/b;
break;
}
}
void cal()
{
for(int i=0;i<len;i++)
{
if(exp[i]==' ')
continue;
else if(opr(exp[i]))
{
a=s.top(); s.pop();
b=s.top(); s.pop();
result(a,b,exp[i]);
s.push(res);
}
else
{
int z=int(exp[i])-'0';
op=op*10+z;
if(exp[i+1]==' ')
{
s.push(op);
op=0;
}
}
}
}
void display()
{
cout<<"\n\nResult is:"<<s.top();
}
};
int main()
{
test t;
t.getdata();
t.cal();
t.display();
cout<<"\n/*\nName-Sanjampreet Singh\nRoll Number-1507967\n*/";
}

Output:


Comments

Popular posts from this blog

Program to illustrate the concept of templates.

To create an html file to implement the concept of margin, padding using cascading style sheets.

To configure the IP address for a computer connected to LAN