Coders Packet

Infix to Postfix Expression Converter and Evaluator in C++

By Dhruv Prakash Raipure

The packet eases your work by converting Infix expression to a corresponding Postfix expression structure in C++ and finally evaluating the result of the expression.

The Infix to Postfix Expression Converter and Evaluator uses the standard library in C++ , bits/stdc++.h. In an infix expression operators are written in-between their operands whereas in Postfix expression the operator is placed after the operands. It is imported into the package so that we can use the stack data structure functionalities from the package. The package takes a standard input of a numeric expression consisting of single digit numbers and binary operators(+,-,*,/,^). It follows the BODMAS rule while evaluating the expressions.

The code consists of 4 main functions.
1. Function infixToPostfix. It takes an expression as a parameter in the form of a string that works through the expression using a stack logic and returns the postfix expression of the passed infix expression to the function.

2. Function evaluatePostfix. The returned postfix expression needs to be evaluated and displayed. It takes the postfix expression in a string form as a parameter and evaluates the result. Hence returning it to the main function.

Two helper functions were used.
1. Function evaluate. It takes up two operands and the corresponding operator between them and returns the result.
2. Function precedence. It takes up an operator in character form and assigns a precedence/priority value to the corresponding operator.

The package produces two outputs. First is the resultant postfix expression of the input infix expression. And second the evaluated result of the input infix expression.


Sample Input/Output

The link above displays a sample input/output for the package. The first line is input Infix Expression which we need to evaluate. The result on 2nd line is the Postfix Expression of given Infix Expression and the last line shows the result after evaluating the expression.

Download Complete Code


No comments yet