Wednesday, 12 February 2014

Infix to Postfix cprogram

aim: to implement a infix to post fix c-program:

program:

#include<ctype.h>
#include<stdio.h>
char stack[80];
int top=-1;
char pop();
void main()
{
char instring[80],outstring[80];
int l,p=0,i;
clrscr();
printf("Enter the infix expression\n");
scanf("%s",instring);
l=strlen(instring);
for(i=0;i<l;i++)
{
if((toupper(instring[i])>='A')&&(toupper(instring[i])<='Z'))
outstring[p++]=toupper(instring[i]);
else if(instring[i]=='(')
push(instring[i]);
else if(instring[i]==')')
{
while(stack[top]!='(')
outstring[p++]=pop();
pop();
}
else
{
while(stack_preced(stack[top])>=in_preced(instring[i]))
outstring[p++]=pop();
push(instring[i]);
}
}
while(top>=0)
outstring[p++]=pop();
outstring[p--]='\0';
printf("postfix expresion=%s",outstring);
getch();
}
stack_preced(char x)
{
switch(x)
{
case '+':
case '-':return(1);
case '*':
case '/':return(2);
case '$':return(3);
case '(':return(0);
}
}
in_preced(char x)
{
switch(x)
{
case '+':
case '-':return(1);
case '*':
case '/':return(2);
case '$':return(3);
case '(':return(4);
}
}
push(char c)
{
stack[++top]=c;
}
char pop()
{
char c;
c=stack[top];
top--;
return(c);
}


No comments:

Post a Comment