In Data Structures the program infix to post fix using stack is very important. There for here is an example for this program. Here we use a stack named stack to store in-stack elements.
/* This is a program to turn a infix expression into post-fix expression and then evaluate the expression */
/* This is a program to turn a infix expression into post-fix expression and then evaluate the expression */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void push(char);
char pop();
int prt(char);
int eval(char *);
int top=-1;
char stack[30];
main()
{
int i=0,k=0;
char infix[30],postfix[30];
printf("Enter the expression ");
scanf("%s",infix);
for(i=0;i<strlen(infix);i++)
{
if(isdigit(infix[i]))
postfix[k++]=infix[i];
else if(top==-1||prt(infix[i])>prt(stack[top]))
{
postfix[k++]=' ';
push(infix[i]);
}
else
{
while(prt(infix[i])<=prt(stack[top])&&top>-1)
postfix[k++]=pop();
push(infix[i]);
}
}
while(top>-1)
postfix[k++]=pop();
postfix[k]='\0';
printf("The postfix expression is %s\n",postfix);
printf("The result is %d\n",eval(postfix));
}
void push(char a)
{
stack[++top]=a;
return;
}
char pop()
{
return stack[top--];
}
int prt(char a)
{
if(a=='+'||a=='-') return 1;
else if(a=='*'||a=='/') return 2;
}
int eval(char *str)
{
int a[30],i,n=-1,j=0;
char temp[5];
for(i=0;str[i]!='\0';i++)
{
if(isdigit(str[i]))
temp[j++]=str[i];
else if(str[i]==' ')
{
temp[j]='\0';
a[++n]=atoi(temp);
j=0;
}
else
{
if(j!=0)
{
temp[j]='\0';
a[++n]=atoi(temp);
j=0;
}
if(str[i]=='+')
a[n-1]=a[n-1]+a[n];
else if(str[i]=='-')
a[n-1]=a[n-1]-a[n];
else if(str[i]=='*')
a[n-1]=a[n-1]*a[n];
else if(str[i]=='/')
a[n-1]=a[n-1]/a[n];
n--;
}
}
return a[0];
}
The output of this program......
Oh!!!! what you have done! This is Wyes who can solve any complicated problem easily.A grand thanks to you for this cooperation.
ReplyDelete