A C++ program that converts infix expressions to prefix notation and calculates the result.
This calculator application allows users to:
- Enter infix expressions
- Convert infix expressions to prefix notation
- Calculate the result of arithmetic operations
The program implements data structures (stack and queue) to efficiently handle the conversion and calculation processes.
- Supports the following operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Exponentiation (^)
- Modulo (%)
- Input validation to ensure valid infix expressions
- User-friendly menu interface
- Decimal precision (results displayed with 2 decimal places)
The program is built using the following components:
- Stack: Two stack implementations:
StackChar
: Used for storing operators during conversionStackInt
: Used for storing numeric values during calculation
- Queue: Used for temporary storage during the conversion process
infixToPrefix()
: Converts infix expressions to prefix notationcalculatePrefix()
: Evaluates prefix expressions to produce the final resultisOperator()
: Checks if a character is an operatorprecedence()
: Determines the precedence of operators for correct order of operations
The infix to prefix conversion follows these steps:
- Reverse the infix expression
- Process each character from right to left:
- If operand, add to queue
- If operator, handle according to precedence rules
- Handle parentheses appropriately
- After processing, pop remaining operators from stack to queue
- Dequeue elements and form the prefix expression
The prefix calculation algorithm:
- Process the prefix expression from right to left
- Push operands onto the stack
- When an operator is encountered, pop two operands and apply the operation
- Push the result back onto the stack
- Continue until the expression is fully processed
- The final value in the stack is the result
- Run the program
- Select an option from the menu:
- Option 1: Enter an infix expression
- Option 2: View the converted prefix expression
- Option 3: Calculate and display the result
- Option 0: Exit the program
- Follow the prompts to enter expressions and navigate through the application
Input (infix): 5+4*2
Converted to prefix: + 5 * 4 2
Result: 13.00
- Fadhillah Maulana - 1303210039
- Irfan Zharauri Nanda Sudiyanto - 1303210006
- CodeBlocks IDE
- GCC Compiler
- C++ Standard Libraries