Evaluating a Postfix Expression Using a Stack -Code C++

I've got accomplished web development with expertise in various programming languages including PHP, Laravel, C#, and C++. My curiosity to learn more and my passion for coding drives me to constantly enhance my skills and create exceptional digital experiences.
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 namedoperandsto store the operands during the evaluation of the postfix expression.for (char c : postfix) {: This is a loop that iterates over each charactercin thepostfixstring.if (isdigit(c)) {: This condition checks if the current charactercis a digit (an operand).double operand = c - '0';: Ifcis a digit, it subtracts the ASCII value of '0' fromcto convert it to the corresponding numeric value and assigns it to theoperandvariable.operands.push(operand);: Theoperandis pushed onto theoperandsstack.else if (c == '^') {: This condition checks if the current charactercis the exponentiation operator '^'.double op2 =operands.top();: Ifcis the exponentiation operator, it retrieves the top operand (op2) from theoperandsstack.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 onop1raised to the power ofop2, and the result is stored in theresultvariable.operands.push(result);: Theresultis pushed back onto theoperandsstack.
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
operandsstack are popped and stored in variablesop2andop1, 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 toop1andop2.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
op1andop2, and the result is computed.The computed result is then pushed back onto the
operandsstack 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 variablepostfixExpressionwith 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 theevaluatePostfixExpressionfunction and passes thepostfixExpressionas an argument. The function evaluates the postfix expression and returns the result, which is stored in theresultvariable 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.


