NAV BAR

Monday 8 August 2016

Infix to Postfix Evaluation

#include<stdio.h>
#include<ctype.h>
#include<String.h>
#define MAX 100
char stack[MAX];
int top =-1;
void push(char);
char pop();
int priority(char);
void InfixPostfix(char [],char[]);
void main()
{
    char infix[20],postfix[20];
    printf("Enter a infix expression\n");
    scanf("%s",infix);
    InfixPostfix(infix,postfix);
    printf("Postfix is  %s",postfix);
    getch();
}
void InfixPostfix(char infix[],char postfix[])
{
    int i,j=0;
    char temp;
    for(i=0;infix[i]!='\0';i++)
    {
        if(infix[i]=='(')
        {
            push(infix[i]);
        }
        else if(isdigit(infix[i])||isalpha(infix[i]))
        {
            postfix[j] = infix[i];
            j++;
        }
        else if(infix[i]==')')
        {
            if(top==-1)
            {
                printf("Invalid Expression");
                exit(1);
            }
            while((top!=-1)&&(stack[top]!='('))
            {
                postfix[j]=pop();
                j++;
            }
            temp=pop();
        }
        else if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/')
        {
            while((top!=-1)&&(stack[top]!='(')&&(priority(stack[top]>=priority(infix[i]))))
            {
                postfix[j]=pop();
                j++;
            }
            push(infix[i]);
        }
        else
        {
            printf("Incorrect expression\n");
            exit(1);
        }
    }
    while(top!=-1)
    {
        postfix[j]=pop();
        j++;
    }
    postfix[j]='\0';
}
void push(char ch)
{
    top++;
    stack[top]=ch;
}
char pop()
{
    char val;
    val = stack[top];
    top--;
    return val;
}
int priority(char ch)
{
    if(ch=='*'||ch=='/')
        return 1;
    if(ch=='+'||ch=='-')
        return 0;
}

No comments:

Post a Comment