C Program to convert Prefix into INFIX
Write a C Program to convert Prefix into INFIX Expression.Here’s a Simple Program To Convert Prefix To Infix Notation using Stack in C Programming Language.
The Prefix notation is also known as Polish Notation.
Prefix To Infix Example :
Prefix String : : + A B C
Infix String : : ((A+B)C)
Algorithm :
- The Reversed Prefix Expression is pushed on the Stack.
- If the Stack is not Empty, then Pop the elements from the Stack
- If the popped character is an Operator
- Input Opening Parantheses ‘(‘ and print it on the console.
- Display popped character from the Stack.
- Input Closing Parantheses ‘)’ and print it on the console.
- If the popped character is an empty space, then print it on the console.
- Repeat the steps till the Prefix expression is not scanned completely.
Below is the source code for C Program to convert Prefix into INFIX Expression which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
#include <stdio.h> #include <string.h> #include <ctype.h> #include <conio.h> char opnds[50][80],oprs[50]; int topr=-1,topd=-1; pushd(char *opnd) { strcpy(opnds[++topd],opnd); } char *popd() { return(opnds[topd--]); } pushr(char opr) { oprs[++topr]=opr; } char popr() { return(oprs[topr--]); } int empty(int t) { if( t == 0) return(1); return(0); } void main() { char prfx[50],ch,str[50],opnd1[50],opnd2[50],opr[2]; int i=0,k=0,opndcnt=0; printf("Give an Expression = "); gets(prfx); printf(" Given Prefix Expression : %s\n",prfx); while( (ch=prfx[i++]) != '\0') { if(isalnum(ch)) { str[0]=ch; str[1]='\0'; pushd(str); opndcnt++; if(opndcnt >= 2) { strcpy(opnd2,popd()); strcpy(opnd1,popd()); strcpy(str,"("); strcat(str,opnd1); ch=popr(); opr[0]=ch;opr[1]='\0'; strcat(str,opr); strcat(str,opnd2); strcat(str,")"); pushd(str); opndcnt-=1; } } else { pushr(ch); if(opndcnt==1)opndcnt=0; /* operator followed by single operand*/ } } if(!empty(topd)) { strcpy(opnd2,popd()); strcpy(opnd1,popd()); strcpy(str,"("); strcat(str,opnd1); ch=popr(); opr[0]=ch;opr[1]='\0'; strcat(str,opr); strcat(str,opnd2); strcat(str,")"); pushd(str); } printf(" Infix Expression: "); puts(opnds[topd]); getch(); }
OUTPUT : :
FIRST RUN :: Give an Expression = +++++abcde Given Prefix Expression : +++++abcde Infix Expression: ((((a+b)+c)+d)+e) SECOND RUN :: Give an Expression = +-435 Given Prefix Expression : +-435 Infix Expression: ((4-3)+5) THIRD RUN :: Give an Expression = ++a*bcd Given Prefix Expression : ++a*bcd Infix Expression: (a+((b*c)+d))
If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach upto you in the short interval.
Thanks for reading the post.
please provide code for without using stacks.
For above expression code is giving wrong output