Thursday, 24 September 2015

Write a C Program To Convert Infix to Postfix Using Stack

1:  #include<stdio.h>  
2:  #include<conio.h>  
3:  #define SIZE 100  
4:  int top = -1;  
5:  char stack[SIZE];  
6:  void push(char item);  
7:  char pop();  
8:  int is_operator(char symbol);  
9:  int precedence(char symbol);  
10:  void main()  
11:  {  
12:   int i, j;  
13:   char infix_exp[SIZE], postfix_exp[SIZE];  
14:   char item, x;  
15:   clrscr();  
16:   printf("\nEnter the arithmetic expression in Infix notation enclosed in parentheses: \n");  
17:   gets(infix_exp);  
18:   i=0;  
19:   j=0;  
20:   item=infix_exp[i++];  
21:   while(item != '\0')  
22:   {  
23:   if(item == '(')  
24:   {  
25:    push(item);  
26:   }  
27:   else if((item >= 'A' && item <= 'Z') || (item >= 'a' && item <= 'z'))  
28:   {  
29:    postfix_exp[j++] = item;  
30:   }  
31:   else if(is_operator(item) == 1)  
32:   {  
33:    x=pop();  
34:    while(is_operator(x) == 1 && precedence(x) >= precedence(item))  
35:    {  
36:    postfix_exp[j++] = x;  
37:    x = pop();  
38:    }  
39:    push(x);  
40:    push(item);    
41:   }  
42:   else if(item == ')')  
43:   {  
44:    x = pop();  
45:    while(x != '(')  
46:    {  
47:    postfix_exp[j++] = x;  
48:    x = pop();  
49:    }  
50:   }  
51:   else  
52:   {  
53:    printf("\nInvalid Arithmetic Expression.\n");  
54:    getch();  
55:    exit(0);  
56:   }  
57:   item = infix_exp[i++];  
58:   }  
59:   postfix_exp[j++] = '\0';  
60:   printf("\nArithmetic expression in Postfix notation: ");  
61:   puts(postfix_exp);  
62:   getch();  
63:  }  
64:  void push(char item)  
65:  {  
66:   if(top >= SIZE-1)  
67:   {  
68:   printf("\nStack Overflow. Push not possible.\n");  
69:   }  
70:   else  
71:   {  
72:   top = top+1;  
73:   stack[top] = item;  
74:   }  
75:  }  
76:  char pop()  
77:  {  
78:   char item = NULL;  
79:   if(top <= -1)  
80:   {  
81:   printf("\nStack Underflow. Pop not possible.\n");  
82:   }  
83:   else  
84:   {  
85:   item = stack[top];  
86:   stack[top] = NULL;  
87:   top = top-1;  
88:   }  
89:   return(item);  
90:  }  
91:  int is_operator(char symbol)  
92:  {  
93:   if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')  
94:   {  
95:   return 1;  
96:   }  
97:   else  
98:   {  
99:   return 0;  
100:   }  
101:  }  
102:  int precedence(char symbol)  
103:  {  
104:   if(symbol == '^')  
105:   {  
106:   return(3);  
107:   }  
108:   else if(symbol == '*' || symbol == '/')  
109:   {  
110:   return(2);  
111:   }  
112:   else if(symbol == '+' || symbol == '-')  
113:   {  
114:   return(1);  
115:   }  
116:   else  
117:   {  
118:   return(0);  
119:   }  
120:  }  

No comments:

Post a Comment