Professional Documents
Culture Documents
Ceng205 Ders6
Ceng205 Ders6
Data structures
Lecture 6:
EVALUATION of EXPRESSIONS
Evaluation of Expressions
• Example: x=a/b-c+d*e-a*c
• Infix : 2+3*5
• Postfix: 235*+
• Prefix: +2*35
Prefix
Postfix
How to convert infix to prefix?
Move each operator to the left of the operands:
• Infix: (a+b)*c-d/e
• Postfix: ???
• Prefix: ???
Example – 1 (solution)
• Infix: (a+b)*c-d/e
• Postfix: ab+c*de/-
• Prefix: -*+abc/de
Example - 2
• Infix: a/b-c+d*e-a*c
• Postfix: ???
• Prefix: ???
Example – 2 (solution)
• Infix: a/b-c+d*e-a*c
• Postfix: ab/c-de*+ac*-
• Prefix:-+-/abc*de*ac
Example – 3
• Infix: (a/(b-c+d))*(e-a)*c
• Postfix: ???
• Prefix: ???
Example – 3 (solution)
• Infix: (a/(b-c+d))*(e-a)*c
• Postfix: abc-d+/ea-*c*
• Prefix: **/a+-bcd-eac
Expressions
multiply A and B,
A*B+C/D AB*CD/+ +*AB/CD divide C by D,
add the results
add B and C,
A * (B + C) / D ABC+*D/ /*A+BCD multiply by A,
divide by D
divide C by D,
A * (B + C / D) ABCD/+* *A+B/CD add B,
multiply by A
Infix, prefix, postfix
Why postfix?
*symbol=expr[(*n)++];
switch(*symbol){
case ‘(’: return left_parent;
case ‘)’: return right_parent;
case ‘+’: return add;
case ‘-’: return subtract;
case ‘/’: return divide;
case ‘*’: return multiply;
case ‘\0’: return eos;
default: return operand;
}
}
How to evaluate a postfix evaluation?
float eval(void){
char symbol;
precedence token;
float op1, op2;
int n=0;
int top=-1;
4 4 0
2 4 2 1
/ 4/2 0
2 4/2 2 1
- (4/2)-2 0
3 (4/2)-2 3 1
3 ((4/2)-2) 3 3 2
* ((4/2)-2) 3*3 1
+ ((4/2)-2)+(3*3) 0
4 ((4/2)-2)+(3*3) 4 1
2 ((4/2)-2)+(3*3) 4 2 2
* ((4/2)-2)+(3*3) 4*2 1
- ((4/2)-2)+(3*3)-(4*2) 0
62/3-42*+
How to convert infix to postfix?
char expr[]=" (4/(2-2+3))*(3-4)*2";
static int stack_pre[]={0,19,12,12,13,13,13,0};
static int pre[]={20,19,12,12,13,13,13,0};
void postfix(void){
char symbol;
precedence token;
int n=0;
int top=0;
stack[0]=eos;
for(token=get_token(&symbol,&n);token!=eos;token=get_token(&symbol,&n)){
if(token==operand)
printf("%c", symbol);
else if(token==right_parent)
while(stack[top]!=left_parent)
print_token(pop(&top));
pop(&top);
}
else{
while(stack_pre[stack[top]]>=pre[token])
print_token(pop(&top));
push(&top, token);
}
}
while((token=pop(&top))!=eos)
print_token(token)
}
CONVERT an INFIX to POSTFIX
a+b*c
CONVERT an INFIX to POSTFIX
a*(b+c)*d
Exercise to do at home:
1. Write the code that converts infix to prefix.
2. Write the code that evaluates a prefix expression.