C program for infix expression to postfix expression and postfix expression evaluation
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
void push1(char);
char pop1(void);
int operand(char);
int priority(char);
void push2(float);
float pop2(void);
float findval(char);
char expr[100];
char variable[100];
float value[100];
char stack1[100],c;
int top1=-1;
int top2=-1;
char postfix[100];
int nv;
float stack2[100];
float val,val1,val2;
main()
{
int i,j,l,p1,p2,flag;
printf("Enter the no. of variables\n");
scanf("%d",&nv);
printf("Enter the variable names\n");
getchar();
for(i=0;i<nv;i++)
{
scanf("%c",&variable[i]);
getchar();
}
printf("enter the values of variables\n");
for(i=0;i<nv;i++)
{
printf("%c=?",variable[i]);
scanf("%f",&value[i]);
}
printf("enter the infix expression\n");
scanf("%s",expr);
l=strlen(expr);
expr[l]=')';
expr[l+1]='\0';
push1('(');
i=0;
j=0;
while(top1>=0)
{
if(operand(expr[i]))
{
postfix[j++]=expr[i];
}
else if(expr[i]=='(')
{
push1('(');
}
else if(expr[i]==')')
{
c=pop1();
while(c!='(')
{
postfix[j++]=c;
c=pop1();
}
}
else
{
p2=priority(expr[i]);
p1=priority(stack1[top1]);
while(p1>=p2)
{
postfix[j++]=pop1();
p1=priority(stack1[top1]);
}
push1(expr[i]);
}
i++;
}
postfix[j]='\0';
printf("Postfix expression=%s",postfix);
printf("\n");
i=0;
for(i=0;postfix[i]!='\0';i++)
{
if(operand(postfix[i]))
{
val=findval(postfix[i]);
push2(val);
}
else
{
val1=pop2();
val2=pop2();
switch(postfix[i])
{
case '+':
val=val2+val1;
break;
case '-':
val=val2-val1;
break;
case '*':
val=val2*val1;
break;
case '/':
val=val2/val1;
break;
case '^':
val=pow(val2,val1);
break;
default:
{
printf("Error!\n");
exit(0);
}
}
push2(val);
}
}
val=pop2();
printf("The value of expression=%f",val);
printf("\n");
}
void push1(char c)
{
stack1[++top1]=c;
}
char pop1(void)
{
char c;
c=stack1[top1];
top1--;
return c;
}
void push2(float c)
{
stack2[++top2]=c;
}
float pop2(void)
{
float c;
c=stack2[top2];
top2--;
return c;
}
int operand(char c)
{
int i,flag=0;
for(i=0;i<nv;i++)
{
if(variable[i]==c)
{
flag=1;
}
}
return flag;
}
int priority(char c)
{
if(c=='(')
{
return 0;
}
if(c=='+')
{
return 1;
}
if(c=='-')
{
return 1;
}
if(c=='*')
{
return 2;
}
if(c=='/')
{
return 2;
}
if(c=='^')
{
return 3;
}
else
{
printf("Invalid operation\n");
exit(0);
}
}
float findval(char c)
{
int i;
for(i=0;i<nv;i++)
{
if(c==variable[i])
{
return value[i];
}
}
return 0;
}
Output
No comments:
Post a Comment