-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab4.c
More file actions
91 lines (88 loc) · 2.06 KB
/
Copy pathLab4.c
File metadata and controls
91 lines (88 loc) · 2.06 KB
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
91
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 20
char stack[SIZE];
int top = -1;
void push(char elem)
{
stack[++top] = elem;
}
char pop()
{
return (stack[top--]);
}
int precedence(char elem) /* Decides the precedence */
{
switch (elem)
{
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
case '%':
return 3;
case '^':
return 4;
default:
printf("Not a Valid Expression\n");
exit(0);
}
}
main()
{
char infix[20], postfix[20], ch, elem;
int i = 0, k = 0, pr;
printf("Enter the Infix Expression: ");
scanf("%s", infix);
push('#'); /* Initial element of stack. It is a handler */
while ((ch = infix[i++]) != '\0')
{
if (ch == '(') /* Verifying left parenthesis */
{
push(ch);
}
else if (isalnum(ch)) /* Verifying operand */
{
postfix[k++] = ch;
}
else if (ch == ')') /* Verifying right parenthesis */
{
while (stack[top] != '(')
{
postfix[k++] = pop();
if (stack[top] == '#')
{
printf("Not a Valid Expression\n");
exit(0);
}
}
elem = pop(); /* Removing left parenthesis */
}
else /* Verifying operators */
{
pr = precedence(ch);
if (ch == '^')
{
pr++; /* If ^ operator appears more than once evaluation takes place from
right to left */
}
while (precedence(stack[top]) >= pr)
{
postfix[k++] = pop();
}
push(ch); /* Push the operator to stack */
}
}
while (stack[top] != '#') /* Pop from stack till empty */
{
postfix[k++] = pop();
}
postfix[k] = '\0'; /* Make postfix as valid string */
printf("Given Infix Expn: %s\nPostfix Expn: %s\n", infix, postfix);
}