filmov
tv
Infix expression evaluation algorithm with examples
Показать описание
Hey programmers! in this video we are going to learn infix expression evaluation algorithm with examples.
Infix evaluation algorithm:
1. Read the string from the left side(character by character).
2. If it is an operand(number) then push it into the stack.
3. If it is the first operator (+,-,*,/) then push it into the stack.
4. If not the first operator then pop two values out of the stack(one will be the operand and the other operator).
5. If the current character is (*,/) and the popped operator is (+,-) then push the two popped values into the stack(step 4).
precedence from higher to lower:
/ * + -
6. Else for any condition :
val1,val2 (step 4).
val3 (new popped value)
Note 'val2' is the operator.
val3 (+,-,*,/) val1
and push the result into the stack.
7. After (steps 5,6)
push the current character into the stack.
8. When the string is finished repeat step 6 until we are left with a single value in the stack and that will be our answer.
When expression contain brackets small change in Algorithm:
1. when character is ' ( ' push it in to stack.
2. when character is ')' then pop values until we get '('.
Infix evaluation algorithm:
1. Read the string from the left side(character by character).
2. If it is an operand(number) then push it into the stack.
3. If it is the first operator (+,-,*,/) then push it into the stack.
4. If not the first operator then pop two values out of the stack(one will be the operand and the other operator).
5. If the current character is (*,/) and the popped operator is (+,-) then push the two popped values into the stack(step 4).
precedence from higher to lower:
/ * + -
6. Else for any condition :
val1,val2 (step 4).
val3 (new popped value)
Note 'val2' is the operator.
val3 (+,-,*,/) val1
and push the result into the stack.
7. After (steps 5,6)
push the current character into the stack.
8. When the string is finished repeat step 6 until we are left with a single value in the stack and that will be our answer.
When expression contain brackets small change in Algorithm:
1. when character is ' ( ' push it in to stack.
2. when character is ')' then pop values until we get '('.