-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluatePostfixExpression.c
90 lines (84 loc) · 1.85 KB
/
evaluatePostfixExpression.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
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
#define N 50
int stack[N];
int top = -1;
void push(int n){
top ++;
stack[top] = n;
}
int pop(){
if(top == -1){
printf("empty\n");
exit(0);
}
int c = stack[top];
top--;
return c;
}
int power(int x,int n){
if(x == 0)
return 0;
if(n == 0)
return 1;
return x*power(x,n-1);
}
void main(){
printf("EVALUATE POSTFIX EXPRESSIONS\n");
char s[MAX],c;
int a,b,temp;
printf("Enter the postfix expression space seperated\n");
scanf("%[^\n]",s);
for(int i=0;i<strlen(s);i++){
c = s[i];
if (c == ' ' || c == ','){
temp = 0;
continue;
}
else if(c == '+'){
a = pop();
b = pop();
push(a+b);
}
else if(c == '-'){
a = pop();
b = pop();
push(b-a);
}
else if(c == '/'){
a = pop();
b = pop();
push(b/a);
}
else if (c == '*'){
a = pop();
b = pop();
push(a*b);
}
else if (c == '^'){
a = pop();
b = pop();
push(power(b,a));
}
else if(c-48 >= 0 && c-48 <= 9){
temp = c - 48;
do{
i++;
c = s[i];
if(c-48 >= 0 && c-48 <= 9)
temp = (temp*10) + c - 48;
else
break;
}while(c != ' ' || c != ',' || c != '\n');
i--;
push(temp);
}
else{
printf("Invalid input symbol or operator!!\n");
exit(0);
}
}
printf("\n%d\n",pop());
}