C program to convert infix to postfix using stack

Infix to postfix using stack

In this tutorial, we will learn what is mean by infix to postfix conversion and how to convert infix to postfix using stack.

Infix expression : Infix expression is the expression which contains the operator in between to operands.

Example: A+B

Postfix expression : Postfix expression is the expression which contains operands first and then the operator which perform on that operands.

Example: AB+

As above we have seen the infix to postfix conversion we convert infix to postfix using stack.

infix to postfix converter

How to convert infix to postfix

1. First, we take infix expression.

2. We read the expression from left to right.

3. We read this expression one by one and check whether it is operand or operator.

4. If it is operand then we print it and if operator we store it into the stack.

5. In the end, we retrieve operator from the stack and print it.

Infix to postfix example

Convert following infix expression to postfix expression.

Infix expression:  A+B*C

Postfix expression: ABC*+

Infix to postfix algorithm 

1. Start

2. Declare variable

3. Read infix input

4. Convert infix to postfix

5. Print postfix expression

6. End

Program to convert infix to postfix using stack

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#define SIZE 50            #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 infix[50],postfix[50],ch,elem;    int i=0,k=0;    printf(“\n\nEnter Infix Expression : “);    scanf(“%s”,infix);    push(‘#’);    while( (ch=infix[i++]) != ‘\0’)    {        if( ch == ‘(‘) push(ch);        else            if(isalnum(ch)) postfix[k++]=ch;            else                if( ch == ‘)’)                {                    while( s[top] != ‘(‘)                        postfix[k++]=pop();                    elem=pop(); /* Remove ( */                }                else                {       /* Operator */                    while( pr(s[top]) >= pr(ch) )                        postfix[k++]=pop();                    push(ch);                }    }    while( s[top] != ‘#’)     /* Pop from stack till empty */        postfix[k++]=pop();    postfix[k]=’\0′;          /* Make postfix as valid string */    printf(“\nPostfix Expression =  %s\n”,postfix);}


Infix to postfix in c