Monday, 5 October 2026

Evaluation of Postfix Expression

#include <iostream>

#include <stack>

#include <cctype>


using namespace std;


int main() {

    string exp;

    stack<int> s;


    cout << "Enter postfix expression: ";

    cin >> exp;


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

        char ch = exp[i];


        // If character is a number

        if (isdigit(ch)) {

            s.push(ch - '0');

        }

        else {

            // Get second operand

            int b = s.top();

            s.pop();


            // Get first operand

            int a = s.top();

            s.pop();


            // Perform operation

            if (ch == '+') {

                s.push(a + b);

            }

            else if (ch == '-') {

                s.push(a - b);

            }

            else if (ch == '*') {

                s.push(a * b);

            }

            else if (ch == '/') {

                s.push(a / b);

            }

        }

    }


    cout << "Result = " << s.top();


    return 0;

}