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.
Here's a short program that does some arithmetic:
PROGRAM MAIN REAL PI REAL RADIUS, CIRCUM, AREA, DIAM PI = 3.1416 RADIUS = 5. DIAM = 2. * 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 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 again at the formula for area of a circle in our program:
AREA = PI * RADIUS ** 2
According to Fortran's rules of precedence, the exponentiation RADIUS ** 2 is done first; then the result is multiplied by PI. 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:
AREA = (PI * RADIUS) ** 2
In this case we would do the multiplication PI * RADIUS first, then square the result. (This of course would not give us the area of a circle; it's just shown as an example.)
It's often helpful to use "unneccessary" parentheses in order 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 at a glance.
Assignment:
(1) Type the short program above that finds the diameter, 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 program that computes the perimeter and area of a rectangle.