Monday, 5 October 2026

Evaluation of Prefix Expression

 #include <iostream>

#include <stack>

#include <cctype>


using namespace std;


int main() {


    string exp;

    stack<int> s;


    cout << "Enter prefix expression: ";

    cin >> exp;


    // Read from right to left

    for (int i = exp.length() - 1; i >= 0; i--) {


        char ch = exp[i];


        if (isdigit(ch)) {

            s.push(ch - '0');

        }

        else {

            int a = s.top();

            s.pop();


            int b = s.top();

            s.pop();


            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;

}