C program Infix to postfix expression.


Infix to postfix C program :

 #include<stdio.h>

#define MAXSIZE 20

typedef struct stack

{

int data[MAXSIZE];

int top;

}STACK;

int isempty(STACK *ps)

{

return ps->top==-1;

}

int isfull(STACK *ps)

{

return ps->top==MAXSIZE-1;

}

void push(STACK *ps, int num)

{

ps->data[++ps->top]=num;

}

int pop(STACK *ps)

{

int num;

num=ps->data[ps->top];

ps->top--;

return num;

//return ps->data[ps->top--];

}

int peek(STACK *ps)

{

return ps->data[ps->top];

}



int priority(char op) //gives priority of an operator

{

int p;

switch(op)

{

case '(': p=0; break;

case '+': case '-': p=1; break;

case '*': case '/': p=2; break;

case '^': p=3;

}

return p;

}



void convert(char infix[20], char postfix[20])

{

int i,j=0;

char ch, ch1;

STACK s;

s.top=-1;



for(i=0; infix[i]!='\0'; i++)

{

ch=infix[i];

switch(ch)

{

case '(' :

push(&s, ch); break;

case ')':

ch1=pop(&s);

while(!isempty(&s) && ch1!='(')

{

postfix[j++]=ch1;

ch1=pop(&s);

}

break;

case '+': case '-': case '*': case '/': case '^':

while( !isempty(&s) && priority(ch)<=priority(peek(&s)) )

postfix[j++]=pop(&s);

push(&s,ch);

break;

default: //operand

postfix[j++]=ch;

}//end switch

}//end for

while(!isempty(&s))

postfix[j++]=pop(&s);

postfix[j++]='\0';

}



int evaluate(char postfix[20])

{

int i, opnd1, opnd2, value;

char ch;



STACK s;

s.top=-1;

for(i=0; postfix[i]!='\0'; i++)

{

ch=postfix[i];

switch(ch)

{

case '+':

opnd2=pop(&s);

opnd1=pop(&s);

push(&s, opnd1+opnd2);

break;

case '-':

opnd2=pop(&s);

opnd1=pop(&s);

push(&s, opnd1-opnd2);

break;

case '*':

opnd2=pop(&s);

opnd1=pop(&s);

push(&s, opnd1*opnd2);

break;

case '/':

opnd2=pop(&s);

opnd1=pop(&s);

push(&s, opnd1/opnd2);

break;

default:

printf("\nEnter value of operand %c : ", ch);

scanf("%d",&value);

push(&s, value);

}

}

return pop(&s);

}

void main()

{

char infix[20], postfix[20];

int ans;

printf("Enter the infix string :");

scanf("%s",infix);

convert(infix, postfix);

printf("The postfix string is :%s", postfix);

ans=evaluate(postfix);

printf("The answer is %d", ans);

}


Post a Comment

0 Comments