#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
class Stack {
private:
char expr[100];
int arr[100];
int top;
public:
Stack() {
top = -1;
void input() {
cout << "Enter the prefix expression: ";
cin.getline(expr, 100);
strrev(expr); // Reverse the expression for processing
void push(int num) {
arr[++top] = num;
int pop() {
return arr[top--];
}
int evaluate() {
int i = 0;
while (expr[i] != '\0') {
if (expr[i] == ' ') {
i++;
continue;
if (isdigit(expr[i])) {
int num = 0, j = i;
while (isdigit(expr[j])) j++; // Find the length of the number
for (int k = j - 1; k >= i; k--) {
num = num * 10 + (expr[k] - '0'); // Convert to integer
i = j; // Move the index to next character after the number
push(num);
} else {
char ch = expr[i];
int a = pop();
int b = pop();
switch (ch) {
case '+':
push(a + b);
break;
case '-':
push(a - b);
break;
case '/':
if (b == 0) {
cout << "Division by zero!" << endl;
return -1;
push(a / b);
break;
case '*':
push(a * b);
break;
case '^':
push((int)pow(a, b));
break;
default:
cout << "Invalid operator" << endl;
return -1;
i++;
return pop();
};
int main() {
Stack obj;
obj.input();
int res = obj.evaluate();
cout << "The result of the prefix expression is: " << res << endl;
return 0;
}