Arithmetic in Fortran: Using Arithmetic Operators

Much of the work we do using Fortran employs the four basic arithmetic operations:

We also have the exponentiation operator, which raises a number to a power:

The variable in which the result is stored gets placed on the left-hand side of the equation with the formula on the right-hand side. There can be only one formula per statement - that is, there can be only one equals sign in a statement.

A short program that does some arithmetic might look like the following:

      PROGRAM MAIN
      REAL PI
      REAL RADIUS, CIRCUM, AREA, DIAM
      PI = 3.1416
      RADIUS = 5.
      DIAM = RADIUS + RADIUS
      CIRCUM = 2. * PI * RADIUS
      AREA = PI * RADIUS ** 2
      PRINT *, 'THE RADIUS OF THE CIRCLE IS', RADIUS
      PRINT *, 'THE DIAMETER OF THE CIRCLE IS', DIAM
      PRINT *, 'THE CIRCUMFERENCE OF THE CIRCLE IS', CIRCUM
      PRINT *, 'THE AREA OF THE CIRCLE IS', AREA
      STOP
      END

Precedence is the order in which mathematical operations are performed. A formula isn't always evaluated simply from left to right. Instead, some kinds of operations are done before others -- they take precedence -- even if they appear later in the formula. The precedence for arithmetic operators in Fortran is:

Look at the following formula:

      C = 2. + 3.1416 * 5. ** 2 

According to Fortran's rules of precedence, the exponentiation 5. ** 2 is done first; then the result is multiplied by 3.1416; and finally 2. is added. Notice in this case the operations are performed backwards from their order in the formula!

Parentheses can be used to rearrange precedence. In the formula above, we could write:

      C = (2. + (3.1416 * 5.)) ** 2 

In this case we would do the multiplication 3.1416 * 5. first, then add 2., and finally square the result.

It's often helpful to use "unneccessary" parentheses, to improve the clarity of your formulas. Compare the readability of the following two formulas:

      A = 3. * X + 2. * Y + 4. * Z 
      A = (3. * X) + (2. * Y) + (4. * Z)

The two formulas produce the same result, but the second is easier to understand.

Assignment:

(1) Type the short program above that finds the circumference and area of a circle. Compile it, run it and compare the results to hand calculations.

(2) Change all of the variables except PI from REAL to INTEGER. Then re-compile and re-run the program. Explain why the results differ from those for REAL variables.

(3) You are now ready to develop your first program. Write, compile and run a short program that illustrates the effect of precedence on arithmetic operations in Fortran.