In a programming language like FORTRAN, we often need to evaluate arithmetic expressions such as:
(X + 3 * Y) / (Z - H ** 2)
There is a specific set of rules for doing this.
Symbols for operations
In FORTRAN, we use:
We do not have a separate symbol to represent the "remainder" operation, as in "7 divided by 3 has a remainder of 1". To do this, we use the MOD function. (See below.)
Integer and Real values
We do arithmetic with numbers, but in FORTRAN we have two kinds of numbers: Integer and Real. The value of an arithmetic expression is a number, but which kind of number is it?
The way to think about this is one operation at a time. If both arguments are Integer, the result of the operation will be an Integer. Otherwise, the result is Real.
Order of evaluation
Often an expression has a variety of operations in it. It may also contain parentheses. FORTRAN will evaluate an expression with a clear list of priorities:
Another way of saying this is that:
Some people are more comfortable with complicated expressions if there are extra sets of parentheses to make the order cleaer.
Example
Suppose we have:
19 + (10 + 3 * 7) / (20 - 3 ** 2)
We start by evaluating each expression in parentheses:
10 + 3 * 7 = 12 + 21 = 31and
20 - 3 ** 2 = 20 - 9 = 11
We put these in the original expression, and we have:
19 + 31 / 11 = 19 + 2 = 21
Notice that:
Intrinsic Functions
FORTRAN includes a collection of functions to do various kinds of arithmetic for us. Here are a few of them:
This gives us the absolute value of its argument (of the same type). Thus, if X = -3, ABS(X) is 3, and if Y = 14.7, ABS(Y) is 14.7.
This gives us the remainder from a division operation. It makes sense primarily for Integer arguments. Thus, MOD(17, 4) is 1 and MOD(-315, 6) is -5.
This gives us the square root of its argument (a Real value). Thus, SQRT(9.0) is 3.0.
There are many more. (See the textbook.)