Convert Infix to Postfix & Evaluate

Convert Infix to Postfix & Evaluate

Question: This is the code to do so:
#include
using namespace std;

int top=-1;
char postfix[100];
int op[100];
int upper=-1;
int a=0,aa=0;
int check=0;

int pushEval(int b)
{
op[++upper]=b;
return 0;
}

int popEval()
{
return (op[upper--]);
}

int pushElement(char x)
{
postfix[++top]=x;

return 0;
}

char pop()
{
if(top == -1)
{
return 0;
}
else
{
return (postfix[top--]);
}
}

int priority(char x)
{
if(x== '(')
{
return 0;
}
else if((x=='+') || (x=='-'))
{
return 1;
}
else if((x=='*') || (x=='/'))
{
return 2;
}
}

int main()
{
char expr[100];
char eval[100];
char y;
int op1=0,op2=0;

cout << "Enter your expression:" << endl;
cin >> expr;

cout << "Postfix expression:" << endl;
while(expr[a] != '\0')
{
if(isalnum(expr[a]))
{
eval[aa++]=expr[a];
}
else if(expr[a] == '(')
{
pushElement(expr[a]);
}
else if(expr[a] == ')')
{
while((y=pop()) != '(')
{
eval[aa++]=y;
}
}
else
{
while(priority(expr[a]) <= priority(postfix[top]))
{
eval[aa++]=pop();
}
pushElement(expr[a]);
}

a++;
}

while(top!= -1)
{
eval[aa++]=pop();
eval[aa]='\0';

}

cout << "\nPostfix expression:" << endl;
int da=0;
while(eval[da]!='\0')
{
cout << eval[da];
da++;
}
int pa=0;
while(eval[pa]!='\0')
{
if(isalnum(eval[pa]))
{
pushEval(eval[pa]-'0');
}
else
{
op2=popEval();
op1=popEval();

switch(eval[pa])
{
case '+':
pushEval(op1+op2);
break;
case '-':
pushEval(op1-op2);
break;
case '*':
pushEval(op1*op2);
break;
case '/':
pushEval(op1/op2);
break;
}
}

pa++;
}

cout << "\nPostfix evaluated value:" << endl;
cout << popEval();
return 0;
}

Leaderboard

Rank Username Points
1Kavenasiva2915
2Kavitha1390
3celine_lou.616990
4Vaishu 855
5cassiopeia360
6Stevie255
7MOGAN_RAJ175
8singamsingu165
9Preshan96135
10madhu490
11Haresh75
1275
13Haneish60
14Mr.R60
15MingXuan45
16Sudheish 45
17troytan9845
18Aswwinyy30
19Carmen140630
20Anushka_Rao30