Following Code Converts An Infix Expression To Prefix Expression :
#include<stdio.h>
#include<ctype.h> //for isalnum function
#include<string.h>
char stack[50];
int top=-1;
void push(char x)
{
if(top==49)
{printf("Overflow");
}
else{
stack[++top]=x;
}
}
char pop()
{ if(top==-1)
{
return -1;
}
else{
return stack[top--];
}
}
int priority(char x)
{
if(x==')')
{ return 0;
}
else if(x=='+'||x=='-')
return 1;
else if(x=='*'||x=='/')
return 2;
}
main()
{
char infix[50],pre[50];
char x,*e;
int i=0;
printf("Enter The Expression ");
scanf("%s",infix);
strrev(infix); //reversing the infix expression
e=infix;
while(*e!='\0')
{
if(*e==')')
{
push(*e);
}
else if(isalnum(*e))
{
pre[i++]=*e;
}
else if(*e=='(')
{
while((x=pop())!=')')
pre[i++]=x;
}
else
{
while(priority(stack[top])>=priority(*e))
pre[i++]=pop();
push(*e);
}
e++;
} while(top!=-1)
pre[i++]=pop();
strrev(pre); //reversing the result from procedure
printf("Prefix Expression ");
printf("%s",pre);
}
Any Problem Please Contact Us mr.dishantmahajan@gmail.com
Output:
#include<stdio.h>
#include<ctype.h> //for isalnum function
#include<string.h>
char stack[50];
int top=-1;
void push(char x)
{
if(top==49)
{printf("Overflow");
}
else{
stack[++top]=x;
}
}
char pop()
{ if(top==-1)
{
return -1;
}
else{
return stack[top--];
}
}
int priority(char x)
{
if(x==')')
{ return 0;
}
else if(x=='+'||x=='-')
return 1;
else if(x=='*'||x=='/')
return 2;
}
main()
{
char infix[50],pre[50];
char x,*e;
int i=0;
printf("Enter The Expression ");
scanf("%s",infix);
strrev(infix); //reversing the infix expression
e=infix;
while(*e!='\0')
{
if(*e==')')
{
push(*e);
}
else if(isalnum(*e))
{
pre[i++]=*e;
}
else if(*e=='(')
{
while((x=pop())!=')')
pre[i++]=x;
}
else
{
while(priority(stack[top])>=priority(*e))
pre[i++]=pop();
push(*e);
}
e++;
} while(top!=-1)
pre[i++]=pop();
strrev(pre); //reversing the result from procedure
printf("Prefix Expression ");
printf("%s",pre);
}
Any Problem Please Contact Us mr.dishantmahajan@gmail.com
Output: