C++ Program to Evaluate an Expression using Stacks

For solving mathematical expression, we need prefix or postfix form. After converting infix to postfix, we need postfix evaluation algorithm to find the correct answer.

Here also we have to use the stack data structure to solve the postfix expressions.

From the postfix expression, when some operands are found, pushed them in the stack. When some operator is found, two items are popped from stack and then operation is performed in correct sequence. After that the result is also pushed in the stack for future use. After completing the whole expression, the final result is also stored in the stack top.

Input: Postfix expression: 53+62/*35*+
Output: The result is: 39



Input: Postfix expression to evaluate.

Output: Answer after evaluating postfix form.

   for each character ch in the postfix expression, do
      if ch is an operator , then
         a := pop first element from stack
         b := pop second element from the stack
         res := b a
         push res into the stack
      else if ch is an operand, then
         add ch into the stack
   return element of stack top

Example Code

using namespace std;
float scanNum(char ch) {
   int value;
   value = ch;
   return float(value-'0');   //return float from character
int isOperator(char ch) {
   if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
      return 1;    //character is an operator
   return -1;   //not an operator
int isOperand(char ch) {
   if(ch >= '0' && ch <= '9')
      return 1;   //character is an operand
   return -1;   //not an operand
float operation(int a, int b, char op) {
   //Perform operation
   if(op == '+')
      return b+a;
   else if(op == '-')
      return b-a;
   else if(op == '*')
      return b*a;
   else if(op == '/')
      return b/a;
   else if(op == '^')
      return pow(b,a); //find b^a
      return INT_MIN; //return negative infinity
float postfixEval(string postfix) {
   int a, b;
   stack<float> stk;
   string::iterator it;
   for(it=postfix.begin(); it!=postfix.end(); it++) {
      //read elements and perform postfix evaluation
      if(isOperator(*it) != -1) {
         a = stk.top();
         b = stk.top();
         stk.push(operation(a, b, *it));
      }else if(isOperand(*it) > 0) {
   return stk.top();
main() {
   string post = "53+62/*35*+";
   cout << "The result is: "<<postfixEval(post);


The result is: 39

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started