Hello friends here is a sample program to convert infix to postfix expression.
InfixToPostfix.cpp #include<stdio.h> #include<conio.h> int getprec(char); int check(char *); void main() { char a[100],stack[100]; int top=-1,i,j; clrscr(); printf("\nEnter the infix expression:"); gets(a); printf("\nPostfix notation is:"); if(check(a)) { for(i=0;a[i]!='\0';i++) { if((a[i]>=97&&a[i]<=122)||(a[i]>=65&&a[i]<=90)||(a[i]>=48&&a[i]<=57)) printf("%c",a[i]); else if(a[i]==')') { while(top>=0&&stack[top]!='(') { printf("%c",stack[top]); top--; } if(stack[top]=='(') top--; } else { if((stack[top-1]=='(')&&(a[i]!='(')&&top>0) { j=getprec(a[i]); while(j<=getprec(stack[top])&&top>=0&&stack[top]!='(') { printf("%c",stack[top]); top--; } } stack[++top]=a[i]; } } while(top>=0) { printf("%c",stack[top]); top--; } } else printf("\nBrases arenot completely closed"); getch(); } int check(char *a) { int i,l=0,r=0; for(i=0;a[i]!='\0';i++) if(a[i]=='(') l++; else if(a[i]==')') r++; if(l==r) return 1; return 0; } int getprec(char c) { switch(c) { case '+':return 1; case '-':return 1; case '*': case '/': case '%':return 2; default:return 999; } }Have fun.....
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.