Program To Convert Infix To Postfix Expression In C++ Using The Stack Data Structure

Infix expression

An infix expression is an expression in which operators (+, -, *, /) are written between the two operands. For example, consider the following expressions:

Example

A + B
A + B - C
(A + B) + (C - D)

Here we have written '+' operator between the operands A and B, and the - operator in between the C and D operand.

Postfix Expression

The postfix operator also contains operator and operands. In the postfix expression, the operator is written after the operand. It is also known as Reverse Polish Notation . For example, consider the following expressions:

Example

A B +   
A B + C -   
A B C * +
A B + C * D -

Algorithm to Convert Infix to Postfix Expression Using Stack

Following is the algorithm to convert infix expression into Reverse Polish notation.

  • Initialize the Stack.
  • Scan the operator from left to right in the infix expression.
  • If the leftmost character is an operand, set it as the current output to the Postfix string.
  • And if the scanned character is the operator and the Stack is empty or contains the '(', ')' symbol, push the operator into the Stack.
  • If the scanned operator has higher precedence than the existing precedence operator in the Stack or if the Stack is empty, put it on the Stack.
  • If the scanned operator has lower precedence than the existing operator in the Stack, pop all the Stack operators. After that, push the scanned operator into the Stack.
  • If the scanned character is a left bracket '(', push it into the Stack.
  • If we encountered right bracket ')', pop the Stack and print all output string character until '(' is encountered and discard both the bracket.
  • Repeat all steps from 2 to 8 until the infix expression is scanned.
  • Print the Stack output.
  • Pop and output all characters, including the operator, from the Stack until it is not empty.

Let's translate an infix expression into postfix expression in the stack:

Here, we have infix expression (( A (B + D)/E) - F (G + H / K))) to convert into its equivalent postfix expression:

Label No. Symbol Scanned Stack Expression
1 ( (
2 ( ((
3 A (( A
4 * ((* A
5 ( ((*( A
6 B ((*( AB
7 + ((*(+ AB
8 D ((*(+ ABD
9 ) ((* ABD+
10 / ((*/ ABD+
11 E ((*/ ABD+E
12 ) ( ABD+E/*
13 - (- ABD+E/*
14 ( (-( ABD+E/*
15 F (-( ABD+E/*F
16 * (-(* ABD+E/*F
17 ( (-(*( ABD+E/*F
18 G (-(*( ABD+E/*FG
19 + (-(*(+ ABD+E/*FG
20 H (-(*(+ ABD+E/*FGH
21 / (-(*(+/ ABD+E/*FGH
22 K (-(*(+/ ABD+E/*FGHK
23 ) (-(* ABD+E/*FGHK/+
24 ) (- ABD+E/FGHK/+
25 ) ABD+E/FGHK/+-

Program to convert infix expression to postfix expression

Let's create a C++ program that converts infix expression to the postfix expression

Example

#include<iostream>
#include<stack>
using namespace std;
// defines the Boolean function for operator, operand, equalOrhigher precedence and the string conversion function.
bool IsOperator(char);
bool IsOperand(char);
bool eqlOrhigher(char, char);
string convert(string);

int main()
{
string infix_expression, postfix_expression;
int ch;
do
{
cout << " Enter an infix expression: ";
cin >> infix_expression;
 postfix_expression = convert(infix_expression);
 cout << "\n Your Infix expression is: " << infix_expression;
cout << "\n Postfix expression is: " << postfix_expression;
cout << "\n \t Do you want to enter infix expression (1/ 0)?";
cin >> ch;
//cin.ignore(); 
} while(ch == 1);
return 0;
}

// define the IsOperator() function to validate whether any symbol is operator.
/* If the symbol is operator, it returns true, otherwise false. */
bool IsOperator(char c)
{
if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^' )
return true;   
return false;
}

// IsOperand() function is used to validate whether the character is operand.
bool IsOperand(char c)
{
if( c >= 'A' && c <= 'Z')  /* Define the character in between A to Z. If not, it returns False.*/
return true;
if (c >= 'a' && c <= 'z')  // Define the character in between a to z. If not, it returns False. */
return true;
if(c >= '0' && c <= '9')   // Define the character in between 0 to 9. If not, it returns False. */
return true;
return false;
}
// here, precedence() function is used to define the precedence to the operator.
int precedence(char op)
{
if(op == '+' || op == '-')                   /* it defines the lowest precedence */
return 1;
if (op == '*' || op == '/')
return 2;
if(op == '^')                                  /* exponent operator has the highest precedence *
return 3;      
return 0;
}
/* The eqlOrhigher() function is used to check the higher or equal precedence of the two operators in infix expression. */
bool eqlOrhigher (char op1, char op2)
{
int p1 = precedence(op1);
int p2 = precedence(op2);
if (p1 == p2)
{
if (op1 == '^' )
return false;
return true;
}
return  (p1>p2 ? true : false);
}

/* string convert() function is used to convert the infix expression to the postfix expression of the Stack */
string convert(string infix)
{
stack <char> S;
string postfix ="";  
char ch;

S.push( '(' );
infix += ')';

for(int i = 0; i<infix.length(); i++)
{
ch = infix[i];

if(ch == ' ')
continue;
else if(ch == '(')
S.push(ch);
else if(IsOperand(ch))
postfix += ch;
else if(IsOperator(ch))
{
while(!S.empty() && eqlOrhigher(S.top(), ch))
{
postfix += S.top();
S.pop();
}
S.push(ch);
}
else if(ch == ')')
{
while(!S.empty() && S.top() != '(')
{
postfix += S.top();
S.pop();
}
S.pop();
}
}
return postfix;
}

Output:

Input Required

This code uses input(). Please provide values below: