Eval Pre1.Txt

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

float Stack[100];
int sp = -1; // Stack pointer initialized to -1

void push(float op) {


Stack[++sp] = op;
}

float pop() {
if (sp < 0) {
printf("Stack underflow.\n");
exit(1);
}
return Stack[sp--];
}

float eval(char sym) {


float res, op1, op2;

if (sp >= 1) {
op1 = pop(); // Note: First operand is popped first in prefix
op2 = pop();

switch (sym) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
if (op2 != 0)
res = op1 / op2;
else {
printf("Division by zero error.\n");
exit(1);
}
break;
case '^':
res = pow(op1, op2);
break;
default:
printf("Invalid operator: %c\n", sym);
exit(1);
}

return res;
} else {
printf("Invalid operands.\n");
exit(1);
}
}

float evalprefix(char prefix[]) {


char sym;
float table[255], res;
int i;

// Initialize the table


for (int i = 0; i < 255; i++) {
table[i] = -1;
}

int n = strlen(prefix);
for (i = n - 1; i >= 0; i--) {
sym = prefix[i];

if (isalnum(sym)) {
if (isdigit(sym)) {
push(sym - '0'); // Convert character digit to integer
} else { // Assume variable
if (table[(int)sym] == -1) {
printf("Enter the value for %c: ", sym);
scanf("%f", &table[(int)sym]);
}
push(table[(int)sym]);
}
} else {
res = eval(sym);
push(res);
}
}

if (sp == 0) {
return pop();
} else {
printf("Invalid expression.\n");
exit(1);
}
}

int main() {
char prefix[50];

printf("Enter the prefix expression: ");


scanf("%s", prefix);

printf("%s = %f\n", prefix, evalprefix(prefix));

return 0;
}

You might also like