To evaluate an expression, we have to follow certain method in BASIC. The method that BASIC follows is that different operators are given a precedence number or priority level. The highest priority is evaluated first, then we evaluate the operators at he next priority level, and so on. This is known as the hierarchy evaluation of expression.
The hierarchy of different operators are shown in the Table C 2.14 below
Operator
|
Order of Precedence
|
^
|
1
|
*, /
|
2
|
+, -
|
3
|
=.<>,< =, >=,<>
|
4
|
NOT
|
5
|
AND
|
6
|
OR
|
7
|
As you see in the table, Multiplication(*), Division(/), are given equal precedence (i.e. 2). Similarly, Addition and Subtraction are also given equal precedence. The expressions are scanned from left to right. Out of the expression having operators with the same precedence, the left most operators is performed first. Parenthesis (Bracket) expression is evaluated ahead of all others.
Example 11
Suppose we have to evaluate the expression :
x= 12^3 + 25 * 8 -12/4 - (75+25) / (75-25)
the execution takes place in the following order.
1. 75+25 = 100 parenthesis (bracket) expression (left most)
2. 75-25 = 50 parenthesis expression
3. 12^3 = 1728 exponentiation
4. 25*28 = 700 multiplication (let most)
5. 12/4 = 3 division
6. 100/50 = 2 division
7. 1728 + 200 = 1928 addition
8. 1928 - 3 = 1925 subtraction
9. 1925 - 2 = 1923 subtraction
No comments:
Post a Comment