infix to postfix

vg_2007's Avatar
Newbie Member
cn some bdy check my program i am getting a small error in it




Code:
#include<stdio.h>
#include<conio.h>
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
const int size=50;
char infix[size],postfix[size],stack[size];
int top=-1;

int precedence(char ch);
char pop();
char topelement();
void push(char ch);
int braces(char *);

void main()
{
 char ele,elem,st[2];
 int prep,pre,popped,j=0,chk=0;
 strcpy(postfix," ");
 clrscr();
 cout<<"ASSUMPTION: the inflix expression contains single letter variables \n\t"<<"\t and single digit constants only \n\n";
 cout<<"\n ENTER INFIX EXPRESSION ....\n" ;
 gets(infix);
 chk=braces(infix);
 if(chk!=0)
 {
 cout<<"UNBALANCED NO. OF BRACES  \n EXTRA ";
 cout<< (chk==1?"right braces ":"left braces ")<<endl;
 getch();
 exit(1);
 }
 for(int i=0;infix[i]!=	NULL;i++)
 {
 if(infix[i]!='('&&infix[i]!=')'&& infix[i]!='^'&& infix[i]!='*' && infix[i]!='/'&& infix[i]!='+'&& infix[i]!='-')
 {
 postfix[j++]=infix[i];
 }
 else if (infix[i]=='(')
 {
 elem=infix[i];
 push(elem);
 }
 else if(infix[i]==')')
 {
 while((popped=pop())!='(')
	{
	postfix[j++]=popped;
	 }
 }
else
{
elem=infix[i];
pre=precedence(elem);
ele=topelement();
prep=precedence(ele);
if(pre>prep)
push(elem);
else
{
while(prep>=pre)
{
if(ele=='#')
break;
popped=pop();
ele=topelement();
postfix[j++]=popped;
prep=precedence(ele);
}
push(elem);
}
}
}
while((popped=pop())!='#')
postfix[j++]=popped;
postfix[j]='\0';
cout<<"\n POSTFIX: "<<postfix<<endl;
}


int precedence(char ch)
{
switch (ch)
	{
	 case '^':return 5;
	 case '/':return 4;
	 case '*':return 4;
	 case '+':return 3;
	 case '-':return 3;
	 default :return 4;
	 }
	 }

char pop()
{
char ret;
if(top!=-1)
{
ret=stack[top];
top--;
return ret;
}
else
return'#';
}

char topelement()
{
 char ch;
 if(top!=-1)
 ch=stack[top];
 else ch='#';
 return ch;
 }

 void push(char ch)
 {
 if(top!=size-1)
 {
 top++;
 stack[top]=ch;
 }
 }

 int braces(char *s)
 {
 int leftbr,rightbr;
 leftbr=rightbr=0;
 for(int i=0;s[i];i++)
 {
 if(s[i]=='(');
 leftbr++;
 if(s[i]==')')
 rightbr++;
 }
 if(leftbr==rightbr)
 return 0;
 else
 if (leftbr<rightbr)
 return 1;
 else
 return -1;
 }

Last edited by shabbir; 16Oct2008 at 08:44.. Reason: Code block
0
oogabooga's Avatar
Ambitious contributor
Please do two things:
1. Put your code in code blocks so that the indentation is preserved.
2. Be more specific about the error.
Same thing with your other post.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
As already pointed out by oogabooga, Let us know the error and not all of your code with where is the error to find.