Tuesday, August 3, 2010

Order of Operation in Visual Basic

The order of operation for expressions that have more than one operation is the same as for other programming languages.

Evaluate values and calculation symbols in this order:

(1) Values enclosed inside parentheses

(2) Exponentiation

(3) Multiplication and Division

(4) Integer Division

(5) Modulus Division

(6) Addition and Subtraction

The order of precedence is applied to an expression by evaluating the expression from left to right for values within parentheses – within parentheses VB will process the expression from left to right looking for an applying the exponentiation operator, then again from left to right applying the multiplication and division operators, etc. This left to right application of operators continues in pass-after-pass working down the order of precedence.

Use parentheses to control the application of the order of precedence of operations.

· Example #1: (5 + 6) * 2 is evaluated:

o first as 5 + 6 = 11, because the parentheses force the addition operation to be evaluated before the multiplication operation,

o next VB will multiple 11 by 2 to arrive at 22.

· Example #2: 5 + 6 * 2 is evaluated:

o first as 6 * 2 = 12, because the multiplication operator is higher in the order of precedence,

o next VB will add 5 to 12 to arrive at 17.

Work the problems in the following table and record the results. Assume that: X=2, Y=4, and Z=3.

Table 3.4

Problem

Result

X + Y ^ Z

66

16 / Y / X

2

X * ( X + 1 )

6

X * X + 1

5

Y ^ X + Z * 2

22

Y ^ ( X + Z ) * 2

2048

( Y ^ X ) + Z * 2

22

( ( Y ^ X ) + Z ) * 2

38