Program name: program to convert infix expression to post fix



Program description: A program which convert infix to postfix using stacks as data structure in c++ 

Infix to Post fix conversion Program in c++
// data_assigment.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
class postfix{
private:
char value[50];
char value2[50];
char stack[20];
char temp[20];
char head;
int top;
int temp_top;
int j;
public:
postfix(){
strcpy(value,"");
strcpy(stack,"");
strcpy(temp,"");
head='/0';
top=-1;
temp_top=0;
j=0;
}
void scan();
void input();
void push(char);
void pop();
void result();
};
void postfix::pop(){
if(top==-1)
cout<<"Stack is empty";
while(top!=-1){
if(head==')')
{cout<<stack[top];
value2[j]=stack[top];
j++;
top--;
if(stack[top]=='(')
{top--;
break;}
}
else
{
cout<<stack[top];
value2[j]=stack[top];
j++;
top--;
if(stack[top]=='(')
break;
}
}//while end
}
void postfix::push(char temp){
if(top==19)
cout<<"stack is full";
top++;
stack[top]=temp;
}
void postfix::input(){
cout<<"\n\t Program to convert Infix to Post fix";
cout<<"\n\nEnter expression in InFix form = ";
cin>>value;
cout<<"\nThe expression in post fix form is = ";
}
void postfix:: scan(){
int i=0;
while(1){
head=value[i];
if(head==NULL)
break;
i++;
if( head=='(' || head=='*'|| head=='/'||head=='+' || head=='-'||head==')')
{
if(head=='(')
push(head);
else if(stack[top]=='(')
push(head);
else if(head==')')
pop();
else if ((stack[top]=='+' || stack[top]=='-') && (head=='*' || head=='/' ) )
push(head);
else if (top==-1)
push(head);
else
{
pop();
push(head);}
}

else
{cout<<head;temp[temp_top]=head;
temp_top++;
value2[j]=head;
j++;
}

}
pop();
value2[j]=NULL;
j++;
}
void postfix::result(){
int counter=0,final[20],top_final=-1,answer=0,check=0,answer2=0;
cout<<"\n\nNow Enter the values for variables."<<endl;
for(int i=0;i<20;i++)
{
head=value2[counter];
if(head==NULL)
break;
switch(head){
case '+':
answer=final[top_final]+final[top_final-1];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
break;
case '-':
answer=final[top_final-1]-final[top_final];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
break;
case '*':
answer=final[top_final]*final[top_final-1];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
break;
case '/':
answer=final[top_final-1]/final[top_final];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
break;
default:
break;
}
if(head!='+'||head!='*'||head!='-'||head!='/')
{
if(i<temp_top){
cout<<"Enter value for "<<temp[counter]<<" = ";
top_final++;
cin>>final[top_final];
}
}
counter++;
}
if (check<=1)
cout<<"The answer is="<<answer2;
else
cout<<"The answer is="<<answer;
}
int _tmain(int argc, _TCHAR* argv[])
{
postfix object;
object.input();
object.scan();
object.result();
getch();
return 0;
}

0 comments:

Post a Comment

 
Top