0
3.0kviews
Write a C program to convert infix expression to postfix expression

Mumbai University > COMPS > Sem 3 > Data Structures

Marks: 10 M

Year: May 2015

1 Answer
0
22views
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void to_postfix(char infix_temp[],char postfix_temp[])
{
    int i=0,j=0;
    char temp;
    strcpy(postfix_temp,"");
    while(infix_temp[i]!='\0')
    {
        if(infix_temp[i]=='(')
        {
        push(st,infix_temp[i]);  //if '(' found, then
            i++;                 //push it to stack
        }
        else if(infix_temp[i]==')')
        {
            while((top!=-1) && (st[top]!='(')
            {
                postfix_temp[j]=pop(st);
                j++;
            }
            if(top==-1)
            {
                printf("\n incorrect expression");
                exit(1);
            }
            temp=pop(st);       //remove left parenthesis
            i++;
        }

        //check for operator
        else if(infix_temp[i]=='+' || infix_temp[i]=='-' ||    infix_temp[i]=='*' || infix_temp[i]=='/' || infix_temp[i]=='%')  
        {
            while((top!=-1)&& (st[top]!='(') && (get_priority(st[top]) > get_priority(infix_temp[i])))
            {
                postfix_temp[j]=pop(st);
                j++;
            }
            push(st,infix_temp[i]);
            i++;
        }

        //check for operand
        else if(is_digit(infix_temp[i] || isalpha(infix_temp[i]))
        {
            postfix_temp[j]=infix_temp[i];
            j++;
            i++;
        }

        else
        {
            printf("\n incorrect element in expr");
            exit(1);
        }
    }
    while((top!=-1) && (st[top]!='('))
    {
        postfix_temp[j]=pop(st);
        j++;
    }
    postfix_temp[j]='\0';
}

int get_priority(char op)  //assigns priority to operator
{
    if(op=='/' || op=='*' || op=='%')
        return 1;
    elseif(op=='+' || op=='-')
        return 0;
}

void push(char st[],char val)
{
    if(top==MAX-1)
        printf("\n overflow");
    else
    {
        top++;
        st[top]=val;
    }
}

char pop(char st[])
{
    char val='';
    if(top==-1)
        printf("underflow");
    else
    {
        val=st[top];
        top--;
    }
    return val;
}

int main()
{
    char infix[50],postfix[50];
    printf("enter infix expr:");
    gets(infix);
    strcpy(postfix,"");
    to_postfix(infix,postfix);
    printf("\n postfix expr is :");
    puts(postfix);
    getch();
    return 0;
}
Please log in to add an answer.