CONVERT INFIX EXP. TO PREFIX

SOURCE CODE :

//programed by Paras Wadher
MCA
Nagpur university

// PROGRAM TO CONVERT INFIX EXPRESSION INTO PREFIX EXPRESSION

#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<ctype.h>
#include<string.h>
#define SIZE 100

class infix
{
char a[20];
public:
int top;
infix()
{
top=-1;
}
int empty(void);
void push(char);
char pop(void);
char stacktop(void);
int priority(char ch);
int oper(char ch);
};
int infix::priority(char ch)
{
int p=0;
switch(ch)
{
case ‘+’:
case’-‘:
p=1;
break;
case ‘*’:
case ‘/’:
p=2;
break;
case’^’:
p=3;
}
return(p);
}
int infix::oper(char ch)
{
int p=0;
switch(ch)
{
case ‘+’:
case’-‘:
case ‘*’:
case ‘/’:
case’^’:
p=1;
}
return(p);
}
int infix::empty(void)
{
if(top==-1)
return(1);
else
return(0);
}
void infix::push(char item)
{
if(top==SIZE-1)
{
cout<<“Stack is overflow”;
exit(1);
}
top++;
a[top]=item;
}
char infix::pop(void)
{
if(empty())
{
cout<<“Stack underflow”;
exit(1);
}
char ch=a[top];
top–;
return(ch);
}
char infix:: stacktop(void)
{
if(empty())
{
cout<<“Stack underflow”;
exit(1);
}
return(a[top]);
}

void main()
{
char input[SIZE],out[SIZE];
infix f;
int j=0;
clrscr();
cout<<“Enter the infix expression:”;
input[0]='(‘;
do
{
++j;
cin>>input[j];

}while(input[j]!=’#’);
input[j]=’\0′;

int l=strlen(input);

f.push(‘)’);
char x;
int i=l-1;
j=0;
while(!f.empty())
{

if(isalpha(input[i]))
{
out[j++]=input[i];
}
else if(input[i]==’)’)
{
f.push(‘)’);
}
else if(input[i]=='(‘)
{
x=f.pop();
while(x!=’)’)
{
out[j++]=x;
x=f.pop();
}
}
else if(f.oper(input[i]))
{
if(f.priority(f.stacktop()) >= f.priority(input[i]))
{
x=f.pop();
while(f.priority(x) >= f.priority(input[i]))
{
if(input[i]!=’)’)
{
out[j++]=x;
}
x=f.pop();
}
f.push(x);
f.push(input[i]);
}
else
{
f.push(input[i]);
}
}
else
{
cout<<“\n INVALID EXPERASSION\n”;
}
i–;
}
out[j]=’\0′;
for(int k=strlen(out);k>=0;k–)
cout<<out[k];
getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *