0% found this document useful (0 votes)
14 views2 pages

Eval Pre1

Uploaded by

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

Eval Pre1

Uploaded by

rohithsr82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy