SELF-TEST EXERCISES 4.1
4.10 Modules as an aid to program design
Since Chapter 2 we have been designing all our programs with the aid of a structure plan as an aid in planning the logic of our programs. Another important aspect of programming is the design of the program's data structure.
Thus far, all the programs that we have written, or indeed that we have been capable of writing, have had very simple data requirements, consisting of little more than a handful of variables. However, in a real-world environment programs are often manipulating hundreds or thousands of separate items of information and the design and control of this data is every bit as important as the design and control of the program itself. Modules are of great assistance in this as they enable a programmer to group the data in such a way that all those procedures that require access to a particular group can do so by simply using the appropriate module.
This will become particularly relevant when we learn how to process sets of similar data in Chapter 7, but can help in the design of programs even now.
120 Basic building blocks
Consider, for example, a program that will be required to read data relating to a series of experiments, and then to carry out certain preliminary statistical analyses on the data before using it in the calculation of some of the physical properties of the specimens which were the subject of the experiment. The data provided might be as follows:
(1) Date of experiment (day, month, year)
(2) Time experiment started'(hours, minutes, seconds) (3) Time experiment ended (hours, minutes, seconds) (4) Sample number
(5) Material of sample (6) Measurement 1(start) (7) Measurement 1 (end) (8) Measurement 2 (start) (9) Measurement 2 (end) (10) Measurement 3 (start) (11) Measurement 3 (end) (12) Measurement 4 (start) (13) Measurement 4 (end)
The statistical analysis will calculate three further items (14) Statistical measure 1
(15) Statistical measure 2 (16) Statistical measure 3
and the four main analysis programs will calculate four physical properties of the sample, each of which will be required in the calculation of the remaining three physical properties and in the printing of the final analysis of the sample,
(17) Property 1 (18) Property 2 (19) Property 3 (20) Property 4
We can help to design the data structure for our program and for the individual procedures within it by writing the various entities in three columns, The first of these is a short description of the purpose of the entity, the second is its type, and the third its name. A data design for the module that will be used to implement the above data structure might, therefore, look as follows:
Purpose Times at start and end of
experiment
Modules as an aid to program design 121 Name
stats _measurement _1 , etc.
property ~ 1, ... etc.
This information could all be encapsulated in a module" such as the following:
" I~ TYPE (time) :: start_time, end_time INTEGER :: sample_number
The various procedures responsible for reading the data, calculating the various results required, and for outputting those res~lts to the appropriate output device, can then use this module to obtain access to the relevant information. For example, an output procedure might begin as follows:
122 Basic building blocks
SUBROUTINE output_data USE data_design IMPLICIT NONE
PRINT *,"Experiment conducted on ",experiment_date%day, &
"/",experiment_date%month,"/",experiment_date%year PRINT *,"At start time (",start_time%hours,":", &
start_time%mins,":",start_timehecs,") &
&measurements were:"
PRINT *,start_measurement_l PRINT *,start_measurement_2 PRINT *,start_measurement_3 PRINT *,start_measurement_4
In all the programming examples throughout the remainder of this book we shall, when appropriate, present a data design structure as well as a structure plan before starting to write any Fortran code.
SELF-TEST EXERCISES 4.2
1 What is the purpose of a module?
2 What does USEassociation do? How?
3 Why are modules especially important in programs that use derived types?
4 What is the difference between an explicit and an implicit interface for a procedure?
5 Give three situations in which modules are either essential or highly beneficial in Fortran 90 programs.
SUMMARY
• Fortran procedures may be subroutines or functions.
• Intrinsic procedures are a special class of procedures which form part of the Fortran language.
• External procedures are normally implemented as Fortran subprograms.
• A Fortran 90 program consists of one main program unit, and any number of external subprogram program units (function or subroutine), module program units and block data program units.
Summary 123
• A function is given information to operate on by means of one or more arguments, and delivers a single result.
• A subroutine's arguments are used both to receive information to operate on and to return results.
• TheINTENT attribute is used to control the direction in which arguments are used to pass information.
• Many intrinsic functions exist in several versions, each of which operates on arguments of different types; such functions are called generic functions.
• The type of the result of a function can be specified either in the initial FUNCTION statement, or in a declaration of a special result variable having the same name as the function.
• Execution of a function is initiated by the appearance of the function name in an expression; execution of a subroutine is initiated by aCALL statement.
• Only the arguments of a procedure are accessible outside the procedure; all other variables and constants declared in the procedure are local to that procedure.
• Modules allow more than one program unit to have access to the objects declared or defined within the module.
• Objects of derived types can only be used as arguments to procedures if their type is defined in a module which is used by the relevant program units.
• Procedures which are contained within a module have an explicit interface to each other and to any program units which use that module; such an interface is desirable for some security aspects, and essential for some of the language features that will be met in future chapters.
• Procedures provide the basic building block for modular development and top-down program design.
• Modules provide the basic encapsulation device for designing a program's data structure.
• Fortran 90 syntax introduced in Chapter 4:
Initial statements
Function reference
Subroutine call
Module use
SUBROUTINE name (dummy argument list) SUBROUTINE name
type FUNCTION name (dummy argument list) type FUNCTION name ()
FUNCTION name (dummy argument list) FUNCTION name ()
MODULE name
junction_name (actual argument list) function_name ( )
CALL subroutine_name (actual argument list) CALL subroutine_name
USE module_name
124 Basic building blocks Assumed length character declaration Argument intent attribute
External procedure attribute
SAVE statement CONTAINS statement
CHARACTER(LEN=(*)) :: characfer_dummy_arg CHARACTER* (*) :: character_dummy_arg INTENT (intent)
where intent is IN, OUT or INOUT EXTERNAL
SAVE CONTAINS
PROGRAMMING EXERCISES
Most larger programs are structured in such a way that each of the major functions (input of data, calculation of each type of analysis, printing of results) is handled by a different procedure, or group of procedures, which can be written and tested independently. In the following exercises you should write your solutions in this way, even though it may not be strictly necessary.
Write a structure plan for the program before you start coding.
"4.1 Write a subroutine which, when supplied with the coordinates of two points
(XI, YI) and (xz, Yz), calculates the distance of each point from the origin and the distance between the points.
Note that the distance dI of point 1 from the origin is given by the formula
while the distance dbetween the two points is given by
Test your subroutine in a short program to cheek that it works correctly with several different sets of data. .
4.2 Write a function which, when supplied with the coordinates of two points (XI, YI)
and (xz, Yz), calculates the distance between the points.
Test your function to make sure that it works correctly.
Now modify the subroutine that you wrote for Exercise 4.1 so that it uses this function to carry out all the necessaly calculations.
4.3 Write a function to give the logarithm of a number to base b. (Use the equation logbx = 10gIox/logIOb.)
,I"~
"4.4 Write a module that contains four integers. Use this module in a program which contains a main program and three subroutines, one to input three integer values from the keyboard, one to calculate the sum of the three integers, and the third to print the result of adding the three numbers together.
Programming exercises 125 Although a trivial program (to put it mildly!) this approach mirrors that used in
larger programs where each of the three activities may be quite complicated, and the use of a module to enable data to be easily shared is extremely useful.
4.5 A credit card company produces monthly statements for its customers. Each statement shows the following information:
(a) The amount outstanding from last month (b) The interest due on that amount for the month (c) Any payment received since the last statement (d) The total spent with the card since the last statement (e) The total amount now outstanding
The customer can then pay any amount as long as it is at least 5% of the outstanding amount.
Write a program which reads the amount outstanding, details of payments made and total spending, and the current interest rate, and then produces an appropriate statement.
4.6 Write a function which, when supplied with two arguments of type point, as already defined on several occasions, returns the distance between the two points as its result. (Note that this is similar to Exercise 4.2, but using derived type arguments.)
Test your function to ensure that it works correctly.
4.7 A builder, possibly the same one as in Exercise 3.10, wishes to calculate the relative costs of building a wall using different sizes of bricks, and different types of mortar.
The thickness of the wall will always be one brick's depth. Regardless of the size of brick and the type of mortar, the thickness of the mortar will always be
f
inch. Write a program to help her.The program should read the size of the bricks and their cost, the cost of the mortar per cubic inch, and the height and length of the wall. It should calculate how many bricks will be required and their cost, how much mortar is required and its cost, and the total cost (excluding labour!).
4.8 The force F due to gravity between two bodies of masses mr and m2 is given by the formula
where G = 6.673 X lO-Il Nm-2kg-2, ris the distance between the bodies (in metres), and the masses mr and m2 are measured in kilograms.
Write a program that uses aREAL function to evaluate the force of gravity between two bodies given their masses and separation. Define G as a parameter (and think about where it should be specified).
4.9 In Einstein's famous equation E
=
mc2, the energy E is in joules if the mass m is in kilograms and c is the speed of light in metres per second (=2.9979 X 108). Write a126 Basic building blocks
function to calculate the energy equivalent of a given mass. Roughly how much energy is equivalent to the mass of a sugar cube (approximately 1gram)?
4.10 Write a program consisting of a main program and two subroutines. The main program should read up to ten positive numbers. It should then use the first subroutine to calculate the arithmetic mean of these numbers (that is, the sum of the numbers divided by n, the number of numbers) and the second to calculate their geometric mean (the nth root of the product of the n numbers). The main program should then print these two means.
(Note that the nth root of a real value can be obtained by raising it to the power of lin.) Now modify the program so that the subroutines do not have any arguments, but obtain their data, and return their results, through variables made available from a module by USEassociation.
4.11 Write a function whose only argument is a time interval in seconds, and whose result is the same time interval expressed in hours, minutes and seconds. (Hint: the result of the function will have to have a derived type.)
4.12 Write a subroutine that calculates the position, velocity and acceleration of a body undergoing simple harmonic motion using the equations given below:
position
=
a sin(nt+
€)velocity
=
na cos(nt+
€)acceleration
=
-an2 sin(nt+
€)"
Use as starting values n = 3.14159265, €= 0, a = 2.5. Test by specifying your own set of values for t.
4.13 In Example 4.5 we wrote a subroutine which calculated the line joining two points. Using the same derived types, write a further subroutine for the module geometric-procedures which calculates the point at the intersection of two lines. Ignore the possibility that the lines might be parallel and, therefore, have no point of intersection;
we shall see how to deal with this in the next chapter.
4.14 The escape velocity from the surface of a planet (the velocity that a spacecraft must reach to escape from the gravitational field of the planet and travel bff into space) is given by the expression:
where G is the gravitational constant (6.673 X1o-II Nm-2 kg-2), M is the mass of the planet (in kg) and R is the planet's radius (in metres).
Write a function that accepts the planetary mass and radius as its input and returns the escape velocity. Use your function to compare the escape velocities from the Earth, Jupiter and the Moon using the following data:
Planet Earth Moon Jupiter
Mass (kg) 6.0 x 1024
7.4 X 1022
1.9 X 1027
Radius (m) 6.4 x 106
1.7 X 106
7.1 X 107
Programming exercises 127
4.15 Write a program to convert the ecliptic latitude f3 and longitude A of an astronomical objed into right ascension aand declination 8 using the formulae
-1sinAcosf - tanf3 sinf
a=tan A
cos
8 = sin-1(sinf3cosf
+
cosf3sinf sinA)where f = 0.4091. Assume that all quantities are in radians.
(Note: Use theATAN2 intrinsic fundion for the first expression.)
In fad, the right ascension of an astronomical objed is generally given in units of time, where 24 hours equals 360 degrees, while the declination is usually given in degrees.
Write a subroutine to convert the two quantities from radians into these units, and incorporate it into your solution.
I'.:
I;