DS Lab Ia 1
DS Lab Ia 1
2 #include<stdio.h>
3 int stk_precedence(char); //function prototypes
4 int input_precedence(char);
5 char pop();
6 void push(char);
7 char postfix[50],infix[50],s[50];
8 int top=-1; //initially stack is empty
9 void main()
10 {
11 int i,j=0;
12 char ch,elem;
13
14 printf("Enter a Valid Infix Expression\n");
15 gets(infix);
16 push('#');
17 for(i=0;infix[i]!='\0';i++)
18 {
19 ch=infix[i];
20 if(isalnum(ch))
21 postfix[j++]=ch;
22 else if(ch=='(')
23 push(ch);
24 else if(ch==')')
25 {
26 while( s[top]!='(')
27 postfix[j++]=pop();
28 elem=pop();
29 }
30 else
31 {
32 while(stk_precedence(s[top])>=input_precedence(ch))
33 postfix[j++]=pop();
34 push(ch);
35 }
36 }
37 while(s[top]!='#')
38 postfix[j++]=pop();
39 postfix[j]='\0';
40 printf("The Postfix Expression Is: %s\n",postfix);
41 }
42
43 int stk_precedence(char e)
44 {
45 switch(e)
46 {
47 case '+':
48 case '-': return(2);
49 case '*':
50 case '/':
51 case '%': return(4);
52 case '^': return(5);
53 case '(':
54 case '#': return(0);
55 }
56 }
57
58 int input_precedence(char e)
59 {
60 switch(e)
61 {
62 case '+':
63 case '-': return(1);
64 case '*':
65 case '/':
66 case '%': return(3);
67 case '^': return(6);
68 case '(':
69 case '#': return(0);
70 }
71 }
72 void push(char ele)
73 {
74 ++top;
75 s[top]=ele;
76 }
77 char pop()
78 {
79 char e;
80 e=s[top];
81 --top;
82 return e;
83 }
84