Program name: program to convert infix expression to post fix
Program description: A program which convert infix to postfix using stacks as datastructurein c++
// data_assigment.cpp : Defines the entry point for the console appliion.
//
#include "stdafx.h"
#include "iostrm"
#include "conio.h"
using namespace std;
class postfix{
private:
char value[50];
char value2[50];
char stack[20];
char temp[20];
char hd;
int top;
int temp_top;
int j;
public:
postfix(){
strcpy(value,"");
strcpy(stack,"");
strcpy(temp,"");
hd='/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(hd==')')
{cout<<stack[top];
value2[j]=stack[top];
j++;
top--;
if(stack[top]=='(')
{top--;
brk;}
}
else
{
cout<<stack[top];
value2[j]=stack[top];
j++;
top--;
if(stack[top]=='(')
brk;
}
}//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){
hd=value[i];
if(hd==)
brk;
i++;
if( hd=='(' || hd=='*'|| hd=='/'||hd=='+' || hd=='-'||hd==')')
{
if(hd=='(')
push(hd);
else if(stack[top]=='(')
push(hd);
else if(hd==')')
pop();
else if ((stack[top]=='+' || stack[top]=='-') && (hd=='*' || hd=='/' ) )
push(hd);
else if (top==-1)
push(hd);
else
{
pop();
push(hd);}
}
else
{cout<<hd;temp[temp_top]=hd;
temp_top++;
value2[j]=hd;
j++;
}
}
pop();
value2[j]=;
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++)
{
hd=value2[counter];
if(hd==)
brk;
switch(hd){
case '+':
answer=final[top_final]+final[top_final-1];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
brk;
case '-':
answer=final[top_final-1]-final[top_final];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
brk;
case '*':
answer=final[top_final]*final[top_final-1];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
brk;
case '/':
answer=final[top_final-1]/final[top_final];
answer2=answer;
top_final--;
final[top_final]=answer;
check++;
brk;
default:
brk;
}
if(hd!='+'||hd!='*'||hd!='-'||hd!='/')
{
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;
}
No comments:
Post a Comment