0% found this document useful (0 votes)
16 views4 pages

Pre Evaluation

The document contains a C++ program that defines a Stack class for evaluating prefix expressions. It allows the user to input a prefix expression, processes it by reversing the string, and evaluates it using a stack data structure. The program handles basic arithmetic operations and checks for division by zero errors.

Uploaded by

waaasimfke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Pre Evaluation

The document contains a C++ program that defines a Stack class for evaluating prefix expressions. It allows the user to input a prefix expression, processes it by reversing the string, and evaluates it using a stack data structure. The program handles basic arithmetic operations and checks for division by zero errors.

Uploaded by

waaasimfke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

#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;
}

You might also like