3.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<process.h>
#define MAX_SIZE 25
char s[MAX_SIZE];
int top=-1;
void main()
{
void PUSH(char);
char POP();
int PRIORITY(char);
char infix[25],postfix[25];
int i=0,j=0;
clrscr();
PUSH('#');
printf("\n enter a valid infix expression \n\n");
gets(infix);
while(infix[i]! = '\0' )
{
if(isalnum(infix[i]))
postfix[j++]=infix[i];
else if(infix[i] = = '(' )
PUSH(infix[i]);
else if(infix[i] = = ')' )
{
while( s[top]! = '(' )
postfix[j++]=POP();
POP();
}
else if( infix[i] = = '+' || infix[i] = = '-' || infix[i] = = '*' || infix[i] = = '/' )
{
while(PRIORITY(s[top])>=PRIORITY(infix[i]))
postfix[j++]=POP();
PUSH(infix[i]);
}
else
{
printf("\n Illegal operator %c \n",infix[i]);
getch();
exit(0);
}
i++;
}
while(s[top]! = '#' )
postfix[j++]=POP();
postfix[j]='\0';
printf("\n given infix expession is: %s \n\n converted postfix expression is: %s \n",infix,postfix);
getch();
}
void PUSH(char ch)
{
if(top>=MAX_SIZE-1)
{
printf("\n stack overflow \n");
getch();
exit(0);
}
s[++top]=ch;
}
char POP()
{
if(top==-1)
{
printf("\n stack underflow \n");
getch();
exit(0);
}
return s[top--];
}
int PRIORITY(char ch)
{
if(ch = = '(' || ch = = '#' )
return (1);
else if(ch = = '+' || ch = = '-' )
return (2);
else if(ch = = '*' || ch = = '/' )
return (3);
}
Comments
Post a Comment