In: Computer Science
In C++, Convert the math expression (2+3)+4*(6-5) to post fix form and evaluate the post fix expression “3 2 * 3 – 2 /” to a value.
#include<iostream>
#include<ctype.h>
using namespace std;
char stack[20];
char str[50]="32*3-2/";
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
}
void EvalPostfix(char postfix[])
{
int i ;
char ch;
int val;
int A, B ,r;
for (i = 0 ; postfix[i] != ')'; i++)
{
ch = postfix[i];
if (isdigit(ch))
{
push(ch -
'0');
}
else if (ch == '+' || ch == '-' ||
ch == '*' || ch == '/')
{
A = pop();
B = pop();
switch
(ch)
{
case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
}
push(val);
}
}
r=pop();
cout<<r;
}
int main(){
char exp[20]="(2+3)+4*(6-5)";
char postfix[20]="32*3-2/";
char *e, x;
e = exp;
cout<<"Postfix Expression:";
while(*e != '\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
cout<<pop();
push(*e);
}
e++;
}
while(top != -1)
{
cout<<pop();
}
cout<<endl;
cout<<"Postfix Expression Evaluation:";
EvalPostfix(postfix);
return 0;
}