Sunday, 5 February 2017

Infix to Postfix conversion without incorrect expression checking

#include<stdio.h>
#include <process.h>
#define MAX 50
char stack[MAX];
int top=-1;
int getpriority(char);
void push(char);
char pop();
main()
{
    char infix[50],temp,ch,postfix[50];
    int i,j=0;
    printf("enter the infix expression\n");
    scanf("%s",&infix);
    for(i=0; infix[i] != '\0'; i++)
    {
          ch=infix[i];
          if(ch == '(')
                   push(ch);
          else if(ch == ')')
          {
                 while(stack[top]!='(')
                            postfix[j++]=pop();
                  temp=pop();                  // popping the (
           }
           else if(isalnum(ch))
                  postfix[j++]=ch;
           else
           {
                 while(getpriority(stack[top])>=getpriority(ch))
                        postfix[j++]=pop();
                 push(ch);
          }
    }
    while(top != -1)
              postfix[j++]=pop();
     postfix[j]='\0';
     printf("%s",postfix);
}
int getpriority(char ch)
{
if( ch == '*'|| ch == '/'|| ch == '%')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return 0;
}
void push(char item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

char pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
char temp;
temp=stack[top];
top=top-1;
return temp;
}


No comments:

Post a Comment