forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluationOfPostfixExpression.c
81 lines (78 loc) · 2.12 KB
/
EvaluationOfPostfixExpression.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
/*
A postfix expression is a collection of operators and operands in which the operator is placed after the operands.
To evaluate a postfix expression using Stack data structure we can use the following steps...
1.Create an empty stack and start scanning the postfix expression from left to right.
2.If the element is an operand, push it into the stack.
3.If the element is an operator O, pop twice and get A and B respectively. Calculate B operator A and push it back to the stack.
4.When the expression is ended, the value in the stack is the final answer.
*/
#include <stdio.h>
#include <unistd.h>
struct stack
{
int top;
float a[50];
}
s;
int EvalPostfix(char postfix[])
{
float num1,num2,num3;
int i;
s.top = -1;
printf("\n\n Enter the postfix expression: ");
scanf("%s", postfix);
for (i = 0; postfix[i] != '\0'; i++)
{
switch (postfix[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] = postfix[i] - '0';
break;
case '+':
num1 = s.a[s.top--];
num2 = s.a[s.top--];
s.a[++s.top] = num1 + num2;
break;
case '-':
num2 = s.a[s.top--];
num1 = s.a[s.top--];
s.a[++s.top] = num1 - num2;
break;
case '*':
num2 = s.a[s.top--];
num1 = s.a[s.top--];
s.a[++s.top] = num1 * num2;
break;
case '/':
num2 = s.a[s.top--];
num1 = s.a[s.top--];
s.a[++s.top] = num1 / num2;
break;
}
}
}
int main()
{
char postfix[50];
EvalPostfix(postfix);
printf("\n Expression value is %5.2f", s.a[s.top]);
getchar();
}
/*
Sample Case:
Example 1:
Enter the postfix expression: 56*7+
Expression value is :37.00
Example 2:
Enter the postfix expression: 6523+8*+3+*
Expression value is :288.00
*/