Tuesday, 4 September 2018

DS 4

#include<stdio.h>
#include<stdlib.h>
char infix[100],postfix[100],stack[100];
int top=-1;
void push(char);
char pop();
int precedence(char);
void evaluate();
void main()
{
printf("Enter the valid Infix Notation\n");
scanf("%s",infix);
evaluate();
printf("The Infix Expression is %s\n",infix);
printf("The Postfix Expression is %s\n",postfix);
}
void evaluate()
{
int i=0,j=0;
char symb,temp;
push('#');
for(i=0;infix[i]!='\0';i++)
{
symb=infix[i];
switch (symb)
{
case '(':push(symb);break;
case ')':temp=pop();
while(temp!='(')
{
postfix[j]=temp;
j++;
temp=pop();
}
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '$':
case '^': while(precedence(stack[top])>=precedence(symb))
{
temp=pop();
postfix[j]=temp;
j++;
}
push(symb);
break;
default:postfix[j]=symb;j++;break;
}
}
while(top>0)
{
temp=pop();
postfix[j]=temp;
j++;
}
postfix[j]='\0';
}
int precedence(char symbol)
{
int p;
switch(symbol)
{
case '#':p=-1;break;
case '(':
case')':p=0;break;
case '+':
case '-':p=1;break;
case '*':
case '/':
case '%':p=2;break;
case '^':
case '$':p=3;break;
}
return p;
}
char pop()
{
char item;
item=stack[top];
top=top-1;
return item;
}
void push(char item)
{
top=top+1;
stack[top]=item;
}

















x

No comments:

Post a Comment