Infixxx
Infixxx
h>
2 #include<string.h>
3 #include<math.h>
4
5 char infix[20] , postfix[20] ;
6 int stk[20];
7 int top=-1;
8
9
10 void push(char x)
11 {
12 stk[++top]=x;
13 }
14
15
16 int pop()
17 {
18 return (stk[top--]);
19 }
20
21
22 int precedence(char x)
23 {
24 if(x=='^')
25 return 3;
26 if(x=='*'||x=='/'||x=='%')
27 return 2;
28 if(x=='+'||x=='-')
29 return 1;
30 if(x=='('||x==')')
31 return 0;
32 }
33
34
35 void infixPostfix()
36 {
37 int i, j, len;
38 char symbol, next;
39
40 len = strlen(infix);
41
42 j = 0;
43 for(i=0;i<len;i++)
44 {
45 symbol = infix[i];
46 if(symbol!=' ')
47 {
48 switch(symbol)
49 {
50 case '(':
51 push(symbol);
52 break;
53
54 case ')':
55 while((next = pop()) != '(')
56 {
57 postfix[j++] = next;
58 }
59 break;
60
61 case '^':
62
63 case '*':
64
65 case '/':
66
67 case '%':
68
69 case '+':
70
71 case '-':
72 while((top != -1) &&
(precedence(stk[top]) >= precedence(symbol)))
73 {
74 postfix[j++] = pop();
75 }
76 push(symbol);
77 break;
78
79 default:
80 postfix[j++]=symbol;
81 }
82 }
83 }
84
85 while(top != -1)
86 {
87 postfix[j++] = pop();
88 }
89 postfix[j] = '\0';
90
91 }
92
93
94 int evalPostfix()
95 {
96 int i, a, b, len, res;
97 char symbol;
98
99 len = strlen(postfix);
100 for(i = 0; i < len; i++)
101 {
102 symbol = postfix[i];
103
104 if((symbol >= '0') && (symbol <= '9'))
105 {
106 push(symbol - '0');
107 }
108 else
109 {
110 a=pop();
111 b=pop();
112 if(symbol == '^')
113 push(pow(b,a));
114
115 if(symbol == '*')
116 push(b*a);
117
118 if(symbol == '/')
119 push(b/a);
120
121 if(symbol == '%')
122 push(b%a);
123
124 if(symbol == '+')
125 push(b+a);
126
127 if(symbol == '-')
128 push(b-a);
129
130 }
131 }
132
133 res = pop();
134
135 return res;
136
137 }
138
139
140 void main()
141 {
142 printf("\nEnter Any Expression:");
143 scanf("%s",infix);
144
145 infixPostfix();
146
147 printf("\nPostfix Expression Is :");
148 puts(postfix);
149
150 int exp = evalPostfix();
151
152 printf("\nResult Of Expression = %d",exp);
153 }