Expression Parsing Using Stack
Expression Parsing Using Stack
Infix notation is easier for humans to read and understand whereas for electronic machines like
computers, postfix is the best form of expression to parse. We shall see here a program to
convert and evaluate infix notation to postfix notation −
Example
Live Demo
#include<stdio.h>
#include<string.h>
//char stack
char stack[25];
stack[++top] = item;
char pop() {
return stack[top--];
switch(symbol) {
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 3;
break;
case '^':
return 4;
break;
case '(':
case ')':
case '#':
return 1;
break;
switch(symbol) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '(':
case ')':
return 1;
break;
default:
return 0;
int i,symbol,j = 0;
stack[++top] = '#';
for(i = 0;i<strlen(infix);i++) {
symbol = infix[i];
if(isOperator(symbol) == 0) {
postfix[j] = symbol;
j++;
} else {
if(symbol == '(') {
push(symbol);
} else {
if(symbol == ')') {
while(stack[top] != '(') {
postfix[j] = pop();
j++;
} else {
if(precedence(symbol)>precedence(stack[top])) {
push(symbol);
} else {
while(precedence(symbol)<=precedence(stack[top])) {
postfix[j] = pop();
j++;
push(symbol);
while(stack[top] != '#') {
postfix[j] = pop();
j++;
//int stack
int stack_int[25];
stack_int[++top_int] = item;
char pop_int() {
return stack_int[top_int--];
char ch;
int i = 0,operand1,operand2;
if(isdigit(ch)) {
} else {
operand2 = pop_int();
operand1 = pop_int();
switch(ch) {
case '+':
push_int(operand1+operand2);
break;
case '-':
push_int(operand1-operand2);
break;
case '*':
push_int(operand1*operand2);
break;
case '/':
push_int(operand1/operand2);
break;
return stack_int[top_int];
void main() {
convert(infix,postfix);
If we compile and run the above program, it will produce the following result −
Output
Infix expression is: 1*(2+3)
Result is: 5