Wednesday, April 20, 2011

Evaluation of postfix expression

/* program on Evaluation of postfix expression */

#include"stdio.h"
#include"stdlib.h"
#include"math.h"

#define OPT 0
#define OPND 1
#define LP 2
#define RP 3

char infix[100], postfix[100]; /* global variables declare here */
float val[26];

struct stack
{
float info;
struct stack *next;
} *stk;


/* main function here */

main()
{
int i, type;
char ch;
clrscr();
printf("\nEnter a infix expression : ");
scanf("%s",postfix);
for(i=0;postfix[i]!='\0';i++)
{
ch = postfix[i];
type = gettype(ch);
if(type == OPND)
{
printf("Enter value of %c : ",ch);
scanf("%f",&val[ch-65]);
}
}
printf("\nAfter evaluation: %f",(float)evalpostfix());
getch();
}


/* push function here */

push(struct stack *s, float n)
{
struct stack *temp;
temp = (struct stack *)malloc(sizeof(struct stack));
temp->info = n;
temp->next = s;
stk = temp;
}

/* Pop function here */

float pop(struct stack *s)
{
float ch;
if(s!=NULL)
{
ch = s->info;
stk = s->next;
free(s);
}
return ch;
}
int gettype(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%')
return OPT;
else if(ch == '(')
return LP;
else if(ch == ')')
return RP;
else
return OPND;
}

prec(char op)
{
switch(op)
{
case ')':
case '(': return 0;
case '+':
case '-': return 1;
case '*':
case '/':
case '%': return 2;
case '^': return 3;
}
}



float operate(float op1, float op2, char ch)
{
switch(ch)
{
case '+': return op1+op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': if(op2==0)
return 0;
else
return op1/op2;
case'^': return pow(op1,op2);
}
}

/* function to evaluate the postfix expression */

evalpostfix()
{
int i, type;
float op1, op2, res;
char ch;
for(i=0; postfix[i]!='\0'; i++)
{
ch = postfix[i];
type = gettype(ch);
if(type == OPND)
push(stk, val[ch-65]);
else
{
op2 = pop(stk);
op1 = pop(stk);
res = operate(op1, op2, ch);
push(stk, res);
}
}
return (float)stk->info;
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites