-
Notifications
You must be signed in to change notification settings - Fork 0
/
program5.c
79 lines (72 loc) · 1.89 KB
/
program5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define MAX_SIZE 20
int top = -1;
int s[MAX_SIZE];
void push(int item) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
s[++top] = item;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return s[top--];
}
int evaluatePostfix(char postfix[]) {
int i, op1, op2;
char symb;
for (i = 0; postfix[i] != '\0'; i++) {
symb = postfix[i];
if (isdigit(symb)) {
push(symb - '0');
} else {
op2 = pop();
op1 = pop();
switch (symb) {
case '+':
push(op1 + op2);
break;
case '-':
push(op1 - op2);
break;
case '*':
push(op1 * op2);
break;
case '/':
if (op2 == 0) {
printf("Division by zero\n");
return 0;
}
push(op1 / op2);
break;
case '^':
// Implementing exponentiation with a loop
int result = 1;
for (int j = 0; j < op2; j++) {
result *= op1;
}
push(result);
break;
default:
printf("Invalid operator\n");
return 0;
}
}
}
return pop();
}
int main() {
char postfix[MAX_SIZE];
printf("Enter postfix expression: ");
scanf("%s", postfix);
int result = evaluatePostfix(postfix);
if (result != -1)
printf("Result: %d\n", result);
return 0;
}