Please suggest some ways to improve my code for calculating a postfix expression from an infix expression entered by the user. The size of the input (Infix
string) should not exceed 10 charaters since the maximum size of the input string mentioned in the code is 10.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
char Infix[10];
char Symbol[10];
char Postfix[10];
void Push();
void Pop();
int Preced(char, char);
void main()
{
clrscr();
printf("Enter a Infix Expression:");
scanf("%s",&Infix);
Push();
printf("\nPostfix of Entered Expression: %s",Postfix);
getch();
}
void Push()
{
int i=0, j=0, k=0, s=0;
while(Infix[i]!='\0')
{
if(Infix[i]=='('||Infix[i]==')'||Infix[i]=='*'||Infix[i]=='+'||Infix[i]=='-'||Infix[i]=='/'||Infix[i]=='%'||Infix[i]=='^')
{
Symbol[j++]=Infix[i];
}
else if(isalpha(Infix[i]))
{
Postfix[k++]=Infix[i];
}
if(Preced(Symbol[j-2],Symbol[j-1])==1)
{
Postfix[k++]=Symbol[j-2];
Symbol[j-2]=Symbol[j-1];
Symbol[j-1]=NULL;
j=j-1;
}
if(Symbol[j-1]==')')
{
s=j-1;
while(Symbol[--s]!='(')
{
printf("%c ",Symbol[s]);
Postfix[k++]=Symbol[s];
Symbol[s]=Symbol[s+1];
Symbol[s+1]=NULL;
}
}
i++;
}
while(--j>=0)
{
if(Symbol[j]=='^'||Symbol[j]=='*'||Symbol[j]=='/'||Symbol[j]=='%'||Symbol[j]=='+'||Symbol[j]=='-')
Postfix[k++]=Symbol[j];
}
}
int Preced(char c1, char c2)
{
if(c1=='^'&&c2=='^') //equal priorities.
{
return 1;
}
else if((c1=='+'||c1=='-')&&(c2=='+'||c2=='-')) //equal
{
return 1;
}
else if((c1=='*'||c1=='/'||c1=='%')&&(c2=='*'||c2=='/'||c2=='%')) //equal
{
return 1;
}
else if(c1=='^'&&(c2=='*'||c2=='/'||c2=='+'||c2=='-'||c2=='%'))
{
return 1;
}
else if((c1=='*'||c1=='/'||c1=='%')&&(c2=='+'||c2=='-'))
{
return 1;
}
else
{
return -1;
}
}