C Program for Infix to Prefix Conversion.
Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #define SIZE 50 /* Size of Stack */ #include<string.h> #include <ctype.h> char s[SIZE]; int top=-1; /* Global declarations */ push(char elem) { /* Function for PUSH operation */ s[++top]=elem; } char pop() { /* Function for POP operation */ return(s[top--]); } int pr(char elem) { /* Function for precedence */ switch(elem) { case '#': return 0; case ')': return 1; case '+': case '-': return 2; case '*': case '/': return 3; } } main() { /* Main Program */ char infx[50],prfx[50],ch,elem; int i=0,k=0; printf("\n\nRead the Infix Expression ? "); scanf("%s",infx); push('#'); strrev(infx); while( (ch=infx[i++]) != '\0') { if( ch == ')') push(ch); else if(isalnum(ch)) prfx[k++]=ch; else if( ch == '(') { while( s[top] != ')') prfx[k++]=pop(); elem=pop(); /* Remove ) */ } else { /* Operator */ while( pr(s[top]) >= pr(ch) ) prfx[k++]=pop(); push(ch); } } while( s[top] != '#') /* Pop from stack till empty */ prfx[k++]=pop(); prfx[k]='\0'; /* Make prfx as valid string */ strrev(prfx); strrev(infx); printf("\n\nGiven Infix Expn: %s Prefix Expn: %s\n",infx,prfx); } |
Description :
This is the one stop educational site for all Electronic and Computer students. If you want to learn something new then we are here to help. We work on Microcontroller projects, Basic Electronics, Digital electronics, Computer projects and also in basic c/c++ programs.
#Home #Sitemap #Resources #Terms of Use
Copyright©2012 electrofriends.com All Rights Reserved
Contact:info@electrofriends.com
The program shows wrong Answer for 2+3*4-5
The correct answer is -+2*345 but the output will be+2-*345 which is wrong !!!
line 52: while( pr(s[top]) >= pr(ch) )
modify as
while( pr(s[top]) > pr(ch) )
now correct ans.
Btw great simple prog. I searched too many places but never found this.
Hats off.