EXAMPLE PROGRAMS D Revision 30/11/2018
1. Input and output
2. Modules
1. Input and Output
Example 1.1 Illustrating formatted output.
program trigTable
! Compiles a table of sin, cos, tan against angle in degrees
implicit none
integer deg ! Angle in degrees
real rad ! Angle in radians
real, parameter :: PI = 4.0 * atan( 1.0 ) ! Mathematical pi
character(len=*), parameter :: fmthead = "( 1x, a3, 3( 2x, a7 ) )"
character(len=*), parameter :: fmtdata = "( 1x, i3, 3( 2x, f7.4 ) )"
! Formats for headings and data
write( *, fmthead ) "deg", "sin", "cos", "tan"
do deg = 0, 80, 10
rad = deg * PI / 180.0
write( *, fmtdata ) deg, sin( rad ), cos( rad ), tan( rad )
end do
end program trigTable
Alternatively put the formats directly in the write statement:
write( *, "( 1x, a3, 3( 2x, a7 ) )" ) "deg", "sin", "cos", "tan"
…
write( *, "( 1x, i3, 3( 2x, f7.4 ) )" ) deg, sin( rad ), cos( rad ),tan( rad )
or attach the formats to a label:
100 format( 1x, a3, 3( 2x, a7 ) )
110 format( 1x, i3, 3( 2x, f7.4 ) )
…
write( *, 100 ) "deg", "sin", "cos", "tan"
…
write( *, 110 ) deg, sin( rad ), cos( rad ), tan( rad )
…
Writing to file:
open( 33, file="[Link]" ) ! Open file for output
write( 33, fmthead ) "deg", "sin", "cos", "tan"
…
write( 33, fmtdata ) deg, sin( rad ), cos( rad ), tan( rad )
…
close( 33 ) ! Close file (tidiness is a virtue!)
Note: if there is just one output stream then it may be quicker to let the operating system re-direct “standard out” from the console
to the required file. e.g.
[Link] > [Link]
The > operator redirects output to the specified file (here, [Link]). There is a corresponding input redirection < if you have
lots of data that you have to enter from the keyboard; put it in successive lines of a file instead.
Fortran Examples Part D David Apsley
Example 1.2 Illustrating floating-point output.
program expTable
! Program tabulates exp(x)
implicit none
integer :: nstep = 15 ! Number of steps
real :: xmin = 0.0, xmax = 3.0 ! Interval limits
real deltax ! Step size
real x ! Current x value
integer i ! Counter
! Format specifiers
character(len=*), parameter :: fmt1 = "( 1x, a4 , 2x, a10 )"
character(len=*), parameter :: fmt2 = "( 1x, f4.2, 2x, es10.3 )"
deltax = ( xmax - xmin ) / nstep ! Calculate step size
write( *, fmt1 ) "x", "exp" ! Write headers
do i = 0, nstep
x = xmin + i * deltax ! Set x value
write( *, fmt2 ) x, exp( x ) ! Write data
end do
end program expTable
Fortran Examples Part D David Apsley
Example 1.3 Illustrating reading and writing files and data analysis.
The program adds scores from a round of golf.
It reads an input file [Link] of the form
4
6
Hole: 1 2 3 4 5 6
Archie 5 5 11 3 3 7
Barney 3 6 5 5 1 4
Chris 4 3 9 2 4 6
David 4 4 5 3 2 4
where:
the first line is the number of players (here, 4)
the second line is the number of holes (here, 6)
the third line is the set of hole numbers
the remaining lines are the players’ names and their scores for each hole.
The number of players and the number of holes is arbitrary.
Output consists of a table of players and total scores and is written to file [Link].
program golf
implicit none
integer nplayers ! Number of files
integer nholes ! Number of holes
integer score ! Total score
integer i ! Loop counter
integer, allocatable :: shots(:) ! Score for each hole
character(len=15) player ! Player name
character(len=*), parameter :: fmt = "( a, 3x, i3 )" ! Output format
! Open files
open( 21, file="[Link]" )
open( 22, file="[Link]" )
! Read numbers of players and holes
read( 21, * ) nplayers
read( 21, * ) nholes
read( 21, * ) ! Skip a line - nothing needed
! Allocate memory to record the scores of one player
allocate( shots(nholes) )
! Loop round, reading player and scores, writing player and total
do i = 1, nplayers
read( 21, * ) player, shots
score = sum( shots )
write( 22, fmt ) player, score
end do
! Close files and tidy up
close( 21 )
close( 22 )
deallocate( shots )
end program golf
Fortran Examples Part D David Apsley
Example 1.4 Illustrating formatted read, non-advancing i/o and the iostat specifier.
The program converts a passage of text to upper case.
Input file: [Link] (any favourite piece of literature will do!)
Output file: [Link]
program uppercase
implicit none
integer :: io = 0
integer :: lowerToUpper = ichar( 'A' ) - ichar( 'a' )
character ch
open( 10, file="[Link]" ) ! Open files
open( 20, file="[Link]" )
do while ( io /= -1 )
read( 10, "( a1 )", iostat=io, advance="no" ) ch
if ( io == 0 ) then
if ( ch >= 'a' .and. ch <= 'z' ) then ! Change to upper case
ch = char( ichar( ch ) + lowerToUpper )
end if
write( 20, "( a1 )", advance = "no" ) ch ! Write to file
else if ( io == -2 ) then
write( 20, * ) ! Force a line feed
end if
end do
close( 10 ) ! Close files
close( 20 )
end program uppercase
Fortran Examples Part D David Apsley
2. Modules
Example 2.1 Illustrating modules used to share related parameters and variables.
Compilation and linking command for separate files:
nagfor –o [Link] conversion.f90 distance.f90
conversion.f90
module conversion
! Length conversion factors
implicit none
real, parameter :: miles_to_metres = 1609.0
real, parameter :: yards_to_metres = 0.9144
real, parameter :: feet_to_metres = 0.3048
real, parameter :: inches_to_metres = 0.0254
end module conversion
distance.f90
program distance
use conversion ! Make conversion factors available
implicit none
real metres ! Distance in metres
real amount ! Numerical quantity
character units ! Units (i-inches, f-feet, y-yards, m-miles)
print *, "Input amount and units (i-inches, f-feet, y-yard, m-mile)"
read *, amount, units
select case( units )
case( 'I' , 'i' ); metres = amount * inches_to_metres
case( 'F' , 'f' ); metres = amount * feet_to_metres
case( 'Y' , 'y' ); metres = amount * yards_to_metres
case( 'M' , 'm' ); metres = amount * miles_to_metres
end select
print *, "Distance in metres = ", metres
end program distance
Fortran Examples Part D David Apsley
Example 2.2 Illustrating modules as containers of useful routines.
module Physics
! Physical constants and some useful subprograms
implicit none
real, parameter :: SPEED_OF_LIGHT = 3.00e+08 ! (m/s)
real, parameter :: PLANCKS_CONSTANT = 6.63e-34 ! (J s)
real, parameter :: GRAVITATIONAL_CONSTANT = 6.67e-11 ! (N m2/kg2)
real, parameter :: ELECTRON_MASS = 9.11e-31 ! (kg)
real, parameter :: ELECTRON_CHARGE = 1.60e-19 ! (C)
real, parameter :: STEFAN_BOLTZMANN_CONSTANT = 5.67e-08 ! (W/m2/K4)
real, parameter :: IDEAL_GAS_CONSTANT = 8.31e+00 ! (J/K)
real, parameter :: AVOGADRO_NUMBER = 6.02e+23 ! (/mol)
contains
real function pressure( n, T, V )
! Computes pressure by ideal gas law (pV=nRT)
real n, T, V ! Moles, temperature(K), volume(m3)
pressure = n * IDEAL_GAS_CONSTANT * T / V
end function pressure
real function radiation( T, area, emissivity )
! Computes radiative heat flux
real T ! Thermodynamic temperature
real area ! Area of surface
real emissivity
radiation = emissivity * STEFAN_BOLTZMANN_CONSTANT * T ** 4 * area
end function radiation
end module Physics
!=============================================================
program idealGas
! Program to test module Physics
use Physics ! Access module
implicit none
real rmm ! Relative molecular mass
real mass ! Mass (kg)
real temperature ! Temperature (k)
real volume ! Volume (m3)
real moles ! Moles of gas
print *, "Input relative molecular mass"
read *, rmm
print *, "Input mass(kg), temperature(K), volume(m3)"
read *, mass, temperature, volume
moles = 1000.0 * mass / rmm ! Calculate moles of gas
print *, "Pressure = ", pressure( moles, temperature, volume ), "Pa"
end program idealGas
Fortran Examples Part D David Apsley