You are on page 1of 2

Name of the Program:week3

Write a C program that uses stack operations to convert a given infix expression into its postfix
Equivalent, Implement the stack using an array.
#include<stdio.h>
#include<string.h>
int i=0,j=0,top=-1;
char stack[50];
int prec(char);
char inf[50],pf[50];
void push(int);
void postfix(char inf[50]);
int pop();
int main()
{
printf("enter infix expression:\n");
gets(inf);
postfix(inf);
printf("postfix expression is:\n");
puts(pf);
}//end of main
void postfix(char inf[15])
{
char x;
for(i=0;inf[i]!='\0';i++)
{
if(inf[i]=='(')
push(inf[i]);
else if(isalpha(inf[i]))
pf[j++]=inf[i];
else if(inf[i]==')')
{
while(stack[top]!='(')
pf[j++]=pop();
x=pop();
}
else
{
while(prec(stack[top])>=prec(inf[i]))
pf[j++]=pop();
push(inf[i]);
}
enter infix expression:
(a+b)*c/d
postfix expression is:
ab+c*d/
[13r21a0507@mysqldbserver week3]$

}//end of for
while(top!=-1)
{
pf[j++]=pop();
pf[j]='\0';
}//end of postfix()
}
void push(int y)
{
stack[++top]=y;
}//end of push()
int pop()
{
return(stack[top--]);
}//end of pop()
int prec(char c)
{
if(c=='*' || c=='/' || c=='%')
return(5);
else if(c=='+' || c=='-')
return(3);
else if(c=='(')
return(1);
}//end of prec()
Output:
$ ./a.out
enter infix expression:
a+b*c
postfix expression is:
abc*+
[13r21a0507@mysqldbserver week3]$ ./a.out
enter infix expression:
a*b/c-d
postfix expression is:
ab*c/d[13r21a0507@mysqldbserver week3]$ ./a.out

Name of the Program:week3

You might also like