Many scripts perform arithmetic calculations. Figure 6.13 summarizes the arithmetic op-erators. Note the use of various special symbols not used in algebra. The asterisk (*) indi-cates multiplication; the percent sign (%) is the remainder operator, which will be discussed shortly. The arithmetic operators in Fig. 6.13 are binary operators, because each operates on two operands. For example, the expression sum + value contains the binary operator + and the two operands sum and value.
Parentheses are used to group expressions in the same manner as in algebraic expres-sions. For example, to multiply a times the quantity b + c we write:
a * ( b + c )
1. Multiplication, division and remainder operations are applied first. If an expres-sion contains several multiplication, division and remainder operations, opera-tors are applied from left to right. Multiplication, division and remainder operations are said to have the same level of precedence.
2. Addition and subtraction operations are applied next. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction operations have the same level of precedence.
The following is an example of an arithmetic mean (average) of five terms:
The parentheses are required to group the addition operators, because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as
and would not lead to the correct answer.
The following is an example of the equation of a straight line:
No parentheses are required. The multiplication operator is applied first, because multi-plication has a higher precedence than addition. The assignment occurs last, because it has a lower precedence than multiplication and addition.
The following example contains remainder (%), multiplication, division, addition and subtraction operations:
To develop a better understanding of the rules of operator precedence, consider the evaluation of a second-degree polynomial (y = ax2 + bx + c):
Figure 6.15 illustrates the order in which the operators are applied in the preceding second-degree polynomial.
As in algebra, it is acceptable to use unnecessary parentheses in an expression to make the expression clearer. These are also called redundant parentheses. For example, the pre-ceding second-degree polynomial might be parenthesized as follows:
y = ( a * x * x ) + ( b * x ) + c;
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.