C Program for Infix to Postfix Equivalent

Estudies4you

1 #include<stdio.h>
2 void infixtopostfix(char[],char[]);
3 int precedence(char);
4 void main()
5 {
6 char infix[20],postfix[20];
7 //clrscr();
8 printf("\n Enter the Infix_experssion : ");
9 scanf("%s",infix);
10 infixtopostfix(infix,postfix);
11 printf("\nPostfix_expression is : %s",postfix);
12 }
13 void infixtopostfix(char infix[],char postfix[])
14 {
15 char s[20],symbol;
16 int top=-1,i=0,j=0;
17 while(infix[i]!='\0')
18 {
19 symbol=infix[i];
20 switch(symbol)
21 {
22 case '(': ++top;
23 s[top]=symbol;
24 break;
25 case ')': while(s[top]!='(')
26 {
27 postfix[j++]=s[top];
28 top--;
29 }
30 top--;
31 break;
32 case '+':
33 case '-':
34 case '*':
35 case '^':
36 case '/':
37 while(precedence(symbol)<=precedence(s[top])&&top!=-1)
38 postfix[j++]=s[top--];
39 s[++top]=symbol;
40 break;
41 default:postfix[j++]=symbol;
42 }
43 i++;
44 }
45 while(top!=-1)
46 {
47 postfix[j++]=s[top];
48 top--;
49 }
50 postfix[j]='\0';
51 }
52 int precedence(char x)
53 {
54 switch(x)
55 {
56 case '+':
57 case '-': return(1);
58 case '*':
59 case '^': return(3);
60 case '/': return(2);
61 default: return(0);
62 }
63 }
Output:
Enter the Infix_experssion : a+b*c
Post fix_expression is : abc*+
Enter the Infix_experssion : a+(b+c*d)*f
Post fix_expression is : abcd*+f*+
Enter the Infix_experssion : a+(b*c+d)*f
Post fix_expression is : abc*d+f*+
Enter the Infix_experssion : a*(b*c+d)+f
Post fix_expression is : abc*d+*f+

To Top