Infix To Postfix Conversion & Evaluation in C
Infix To Postfix Conversion & Evaluation in C
001 #include<stdio.h>
002 #include<string.h>
003 #include<math.h>
004
005 #define oper(x) (x=='+' || x=='-' || x=='*' || x=='/')
006
007 char in[30], post[30], stack[30];
008 int top=-1;
009
010 void push(char x)
011 {
012 stack[++top]=x;
013 }
014
015 char pop()
016 {
017 return stack[top--];
018 }
019
020 int precedence(char c)
021 {
022 if (c=='+' || c=='-')
023 return 1;
024 if (c=='*' || c=='/')
025 return 2;
026 if (c=='(')
027 return 3;
028 }
029
030 main()
031 {
032 char c;
033 int l,i,j=0,st1[20],k,h,f,eval,s,N;
034 printf("Enter the infix exp<b></b>ression : ");
035 scanf("%s",&in);
036 l=strlen(in);
037 for(i=0;i<=l;i++)
038 {
039 if(oper(in[i]))
040 {
041 post[j++]=' ';
042 while(precedence(in[i])<precedence(stack[top])) //any
problem here?
043 {
044 post[j++]=stack[top];
045 pop();
046 post[j++]=' ';
047
048 }
049 push(in[i]);
050 }
051 else if(in[i]=='\0')
052 {
dreamincode.net/…/57329-infix-to-postf… 1/3
9/24/2010
052 { Infix To Postfix Conversion & Evaluation…
053 while(top!=-1)
054 {
055 post[j++]=' ';
056 post[j++]=stack[top];
057 pop();
058 }
059 }
060 else
061 post[j++]=in[i];
062 }
063 post[j]='\0';
064 printf("Postfix Exp<b></b>ression : %s\n",post);
065 i=0;top=-1;f=0;k=0;
066 while(i<j)
067 {
068 if(oper(post[i]))
069 {
070 f=1;
071 c=post[i];
072 eval=0;
073 switch(c)
074 {
075 case '+':
076 eval=st1[top-1]+st1[top];
077 break;
078 case '-':
079 eval=st1[top-1]-st1[top];
080 break;
081 case '*':
082 eval=st1[top-1]*st1[top];
083 break;
084 case '/':
085 eval=st1[top-1]/st1[top];
086 break;
087 }
088 top--;
089 st1[top]=eval;
090 }
091 else if(post[i]==' ')
092 {
093 if(f==0)
094 {
095 h=i-k;
096 s=0;
097 while(post[h]!=' ')
098 {
099 N=(int)post[h];
100 N=N-48;
101 s=s+N*(pow(10,(k-1)));
102 k--;
103 h++;
104 }
105 st1[++top]=s;
106 }
dreamincode.net/…/57329-infix-to-postf… 2/3
9/24/2010
106 } Infix To Postfix Conversion & Evaluation…
107 k=0;
108 }
109 else
110 {
111 k++;
112 f=0;
113 }
114 i++;
115 }
116 printf("Value : %d\n",st1[top]);
117 }
dreamincode.net/…/57329-infix-to-postf… 3/3