Arithmetic in FORTRAN

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:

  1. Replace each variable involved by its value.

  2. Look for parentheses. If there are parentheses, evaluate the "sub-expression" inside the parentheses. (This applies this list of rules to just that sub-expression.)

  3. Evaluate any exponentiation (**) in the expression.

  4. Working from left to right, look for multiplication (*) and division (/) and evaluate these as they are found.

  5. Working from left to right, look for addition (+) and subtraction (-) and evaluate these as they are found.

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 = 31
and
          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:

There are many more. (See the textbook.)