Table of contents
Code
#include <iostream>
#include <stack>
#include <cmath> // For exponentiation operator (^)
using namespace std;
// Function to evaluate a postfix expression
double evaluatePostfixExpression(string postfix) {
stack<double> operands; // Stack to store operands during evaluation
for (char c : postfix) {
if (isdigit(c)) {
// If character is a digit (operand), convert it to double and push onto the stack
double operand = c - '0';
operands.push(operand);
} else if (c == '^') {
// If character is the exponentiation operator, '^'
// Pop the top two operands from the stack
double op2 = operands.top();
operands.pop();
double op1 = operands.top();
operands.pop();
// Apply exponentiation operation and push the result back onto the stack
double result = pow(op1, op2);
operands.push(result);
} else {
// If character is an operator ('+', '-', '*', '/')
// Pop the top two operands from the stack
double op2 = operands.top();
operands.pop();
double op1 = operands.top();
operands.pop();
// Apply the corresponding operation based on the operator and push the result back onto the stack
switch (c) {
case '+':
operands.push(op1 + op2); // Addition
break;
case '-':
operands.push(op1 - op2); // Subtraction
break;
case '*':
operands.push(op1 * op2); // Multiplication
break;
case '/':
operands.push(op1 / op2); // Division
break;
}
}
}
// The final result is the top element of the stack
return operands.top();
}
int main() {
string postfixExpression = "43+5*"; // Example postfix expression
double result = evaluatePostfixExpression(postfixExpression); // Evaluate the postfix expression
cout << "Postfix Expression: " << postfixExpression << endl; // Print the postfix expression
cout << "Result: " << result << endl; // Print the result
return 0;
}
Output
Explaining:
#include <iostream>
#include <stack>
#include <cmath> // For exponentiation operator (^)
#include <stack>
is used to include the stack library, which provides the stack data structure.#include <cmath>
is used to include the math library for using mathematical functions likepow()
in the code.
// Function to evaluate a postfix expression
double evaluatePostfixExpression(string postfix) {
stack<double> operands; // Stack to store operands during evaluation
for (char c : postfix) {
//value given in function stored in char c
if (isdigit(c)) {
// If character is a digit (operand), convert it to double and push onto the stack
double operand = c - '0'; //acc to ASCI code 0 = 48 so we will conver it into asci
operands.push(operand); //operand is pushed into operands stack
} else if (c == '^') {
// If character is the exponentiation operator, '^'
// Pop the top two operands from the stack
double op2 = operands.top();
operands.pop();
double op1 = operands.top();
operands.pop();
// Apply exponentiation operation and push the result back onto the stack
double result = pow(op1, op2);
operands.push(result);
}
stack<double> operands;
: This creates a stack namedoperands
to store the operands during the evaluation of the postfix expression.for (char c : postfix) {
: This is a loop that iterates over each characterc
in thepostfix
string.if (isdigit(c)) {
: This condition checks if the current characterc
is a digit (an operand).double operand = c - '0';
: Ifc
is a digit, it subtracts the ASCII value of '0' fromc
to convert it to the corresponding numeric value and assigns it to theoperand
variable.operands.push(operand);
: Theoperand
is pushed onto theoperands
stack.else if (c == '^') {
: This condition checks if the current characterc
is the exponentiation operator '^'.double op2 =
operands.top
();
: Ifc
is the exponentiation operator, it retrieves the top operand (op2
) from theoperands
stack.operands.pop();
: The top operand is removed from the stack.double op1 =
operands.top
();
: The next top operand (op1
) is retrieved from the stack.operands.pop();
: The next top operand is removed from the stack.double result = pow(op1, op2);
: The exponentiation operation is performed onop1
raised to the power ofop2
, and the result is stored in theresult
variable.operands.push(result);
: Theresult
is pushed back onto theoperands
stack.
else {
// If character is an operator ('+', '-', '*', '/')
// Pop the top two operands from the stack
double op2 = operands.top();
operands.pop();
double op1 = operands.top();
operands.pop();
// Apply the corresponding operation based on the operator and push the result back onto the stack
switch (c) {
case '+':
operands.push(op1 + op2); // Addition
break;
case '-':
operands.push(op1 - op2); // Subtraction
break;
case '*':
operands.push(op1 * op2); // Multiplication
break;
case '/':
operands.push(op1 / op2); // Division
break;
}
}
}
the else
block is executed when the character c
is an operator ('+', '-', '*', '/'). Here's an explanation of how it works:
The top two operands from the
operands
stack are popped and stored in variablesop2
andop1
, respectively. The order of popping is important because the second operand popped (op2
) will be the one that appears later in the postfix expression.After popping the operands, the corresponding operation based on the operator (
c
) is applied toop1
andop2
.The switch statement is used to determine the specific operation to perform based on the operator. Each case corresponds to one of the supported operators: '+' for addition, '-' for subtraction, '*' for multiplication, and '/' for division.
Depending on the operator, the operation is performed using the values of
op1
andop2
, and the result is computed.The computed result is then pushed back onto the
operands
stack usingoperands.push(result)
. This allows the result to be available for future calculations or as an operand for subsequent operations.The evaluation continues until all characters in the postfix expression have been processed.
return operands.top();
In the evaluatePostfixExpression
function, the line return
operands.top
();
is the final step of the evaluation process. It returns the top element of the operands
stack, which represents the final result of the postfix expression.
int main() {
string postfixExpression = "43+5*"; // Example postfix expression
double result = evaluatePostfixExpression(postfixExpression); // Evaluate the postfix expression
cout << "Postfix Expression: " << postfixExpression << endl; // Print the postfix expression
cout << "Result: " << result << endl; // Print the result
return 0;
}
string postfixExpression = "43+5*";
: This line initializes a string variablepostfixExpression
with the example postfix expression"43+5*"
. You can replace this expression with any valid postfix expression you want to evaluate.double result = evaluatePostfixExpression(postfixExpression);
This line calls theevaluatePostfixExpression
function and passes thepostfixExpression
as an argument. The function evaluates the postfix expression and returns the result, which is stored in theresult
variable of typedouble
.cout << "Postfix Expression: " << postfixExpression << endl;
This line prints the original postfix expression before the evaluation. It provides a visual confirmation of the expression that was evaluated.cout << "Result: " << result << endl;
This line prints the result of the evaluated postfix expression. It displays the computed value after performing the operations defined in the postfix expression.return 0;
This line ends the main function and returns a value of 0 to indicate successful program execution.
Conclusion
the provided code implements a postfix expression evaluator using a stack data structure. It effectively evaluates postfix expressions by iterating over each character and performing the corresponding operations based on the type of character encountered. The code showcases the usage of stacks to store operands during the evaluation process and demonstrates the power and versatility of stack data structures in solving postfix expression problems.