-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23_postfix_expression_evaluvation.c
52 lines (52 loc) · 1.06 KB
/
23_postfix_expression_evaluvation.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
//Govind J Nair
//S3-D
//23
#include <stdio.h>
#include <stdlib.h>
int power(int base, int exponent) {
if (exponent==1) {
return 1;
} else {
return base*power(base, exponent-1);
}
}
int evaluvate(int operand1, int operator, int operand2) {
switch(operator) {
case '+':
return (operand1+operand2);
case '-':
return (operand1-operand2);
case '*':
return (operand1*operand2);
case '/':
return (operand1/operand2);
case '^':
return (power(operand1, operand2));
default:
printf("Invalid operator");
exit(0);
}
}
int isOperand(char symbol) {
if ((symbol>=48 && symbol<=57)) {
return 1;
}
return 0;
}
int main() {
char postfix[20];
int stack[100];
int i, top=-1, x, y;
printf("Enter the postfix expression : ");
scanf(" %s", postfix);
for (i=0; postfix[i] != '\0'; i++) {
if (isOperand(postfix[i])) {
stack[++top] = postfix[i]-48;
} else {
y = stack[top--];
x = stack[top];
stack[top] = evaluvate(x, postfix[i], y);
}
}
printf("%d\n", stack[top]);
}