Saturday 28 September 2024

Write a program to Evaluation of a postfix expression

 #include <iostream>

#include <stack>

#include <string>

using namespace std;


int performOperation(int operand1, int operand2, char operation)

{

    switch (operation) {

    case '+':

        return operand1 + operand2;

    case '-':

        return operand1 - operand2;

    case '*':

        return operand1 * operand2;

    case '/':

        return operand1 / operand2;

    default:

        return 0;

    }

}

// Function to evaluate the postfix expression

int evaluatePostfixExpression( string& expression)

{

    stack<int> stack;

     for (int i = 0; i < expression.length();i++) {

        char c = expression[i];

        // Check if the character is a digit isdigit 0-9

        if (isdigit(c)) {

            // Convert char digit to int and push onto the stack

            stack.push(c - '0');

       //  c is digit and ‘0’ ascii value is 48 , ‘1’ ascii value is 49 

   //‘2’ ascii value is 50, ‘3’ ascii value is 51,

      //49-48=1

   } else {

            // Pop the top two elements for the operation

            int operand2 = stack.top();

            stack.pop();

            int operand1 = stack.top();

            stack.pop();

            // Perform the operation and push the result back onto the stack

            int result = performOperation(operand1, operand2, c);

            stack.push(result);

        }

    }

    // The final result should be the only item left in the stack

    return stack.top();

}

int main()

{

    string expression2;


    //  the user for input

    cout << "Enter a postfix expression";

       cin>>expression2;

    int result = evaluatePostfixExpression(expression2);

      cout << "Result of Postfix Expression” <<result;


    return 0;

}