C Program to convert Infix To Postfix Expression Using Stack


By on 1:13 PM

This is a  short, easy to understand and functional C Program which converts Infix Expression to Postfix Expression.i.e. (a+b)*c/(d-e)+f   To  ab+cde-/*f+.

Source Code:
#include<ctype.h>
#include<stdio.h>
void push(char elem);
int pr(char elem);
char pop();
char infx[50],pofx[50],ch,elem,s[50];
int top=-1;       /* Global declarations */
void main()
{                         /* Main Program */
    int i=0,k=0;
    push('#');
    printf("\nEnter the Infix Expression: ");
    scanf("%s",infx);
    while( (ch=infx[i++]) != '\0')
    {
        if( ch == '(')
push(ch);
        else if(isalnum(ch))
pofx[k++]=ch;
            else if( ch == ')')
                {
                    while( s[top] != '(')
                        pofx[k++]=pop();
                    elem=pop(); /* Remove ( */
                }
                else
                {       /* Operator */
                    while( pr(s[top]) >= pr(ch) )
                        pofx[k++]=pop();
                    push(ch);
                }
    }
    while( s[top] != '#')     /* Pop from stack till empty */
        pofx[k++]=pop();
    pofx[k]='\0';          /* Make pofx as valid string */
    printf("\n\nInfix Expression: %s\nPostfix Expression: %s\n",infx,pofx);
}
void 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;break;
    case '(': return 1;break;
    case '+': return 2;break;
    case '-': return 2;break;
    case '*': return 3;break;
    case '/': return 4;break;
    }
}
//www.sparajuli.com.np/

This program is successfully compiled and run in Dev C++ and working.If you have any query, ask below in comment section.

About Syed Faizan Ali

Faizan is a 17 year old young guy who is blessed with the art of Blogging,He love to Blog day in and day out,He is a Website Designer and a Certified Graphics Designer.