CPP Program to Evaluate Postfix Expression using Stack

Postfix Evaluation using stack is one such data structure that our compilers and interpreters use to evaluate any expression. They do not directly evaluate any infix expression using operator preference, instead of that they firstly convert any given infix expression into postfix expression and then evaluate it.

Following CPP program evaluate any given postfix expression using STACK. This program assumes that the largest postfix expression will have a maximum of 30 chars. This program was developed using DevC++, a famous C++ IDE using GCC compiler.

We are assuming here that you are comfortable with Link List and STACK concepts. If not please check our programs on link list and STACK.

/*
 * C++ Program to Evaluate an Expression postfix expression using Stacks
 */
#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;

int stack[100];
int m=0;
void push(int value)
{
	if(m>=100)
		cout<<"\n Stack full";
	else{
		stack[m]=value;
		m++;
	}
}
int pop(){
	int value= -1;
	if(m<=0)
		return value;
	else
	{
		value = stack[m];
		m= m-1;
		return value;
	}
	
}

int main()
{
    char x[30];
    int a, b;
    cout<<"Enter Your postfix Expression without spaces :";
    cin>>x;
    for (int i = 0; i < strlen(x); i++)
    {
        if (x[i] >= 48 && x[i] <= 57)
            push(x[i]-'0');
        else if (x[i] >= 42 && x[i] <= 47) //42 mul, 43, plus , 45 minus and 47 divide
        {
            a=pop();
            b=pop();
            switch(x[i])
            {
            case '+':
                push(a+b);
                break;
            case '-':
                push(a-b);
                break;
            case '*':
                push(a*b);
                break;
            case '/':      
                push(a/b);
                break;
            }
        }
    }
    cout<<"ans is "<<pop()<<endl;
    getch();
}

Another program that you must try with this program is- CPP program to convert an infix expression to postfix expression using STACK.

Above postfix expression evaluation program only works with arithmetic operators if there are logical operators than the above program is not helpful but the same way you can extend.

Output of postfix Evaluation program using stack

nter the balanced expression
456+*
Answer is :6

 

Leave a Reply

Your email address will not be published. Required fields are marked *