You are on page 1of 179

Introduction to

Programming
using
Fortran 95
Ed Jorgensen
June, 2013
Version 1.5
Cover Diagram
The cover image is the plotted output from the chaos game program from chapter 11. The
image was plotted with !"plot.
Copyright
Ed Jorgensen 2013
#ou are free$
to %hare & to cop', distri(ute and transmit the wor)
to *emi+ & to adapt the wor)
"nder the following conditions$
,ttri(ution. #ou must attri(ute the wor) to -.ntroduction to /rogramming using 0ortran
152 3(ut not in an' wa' that suggests that the authors endorse 'ou or 'our use of the
wor)4.
%hare ,li)e. .f 'ou alter, transform, or (uild upon this wor), 'ou ma' distri(ute the
resulting wor) onl' under the same, similar or a compati(le license.
0or an' reuse or distri(ution, 'ou must ma)e clear to others the license terms of this wor). The
(est wa' to do this is with a lin) to
http$55creativecommons.org5licenses5('6sa53.05
,n' of the a(ove conditions can (e waived if 'ou get permission from the cop'right holder.
!othing in this license impairs or restricts the author7s moral rights.
ii
Table of Contents
1 Introduction....................................................................................................................................... 1
1.1 8h' 9earn /rogramming............................................................................................................ 1
1.2 0ortran......................................................................................................................................... 1
1.3 :omplete 0ortran 15 ;ocumentation.......................................................................................... 1
1.< 8hat .s , /rogram...................................................................................................................... 2
1.5 =perating %'stem........................................................................................................................ 2
2 Computer Organization.................................................................................................................... 3
2.1 ,rchitecture =verview................................................................................................................ 3
2.2 :ompiler...................................................................................................................................... <
2.3 .nformation *epresentation......................................................................................................... <
2.3.1 ;ecimal !um(ers................................................................................................................ <
2.3.2 >inar' !um(ers................................................................................................................... 5
2.3.3 :haracter *epresentation..................................................................................................... 5
2.< E+ercises...................................................................................................................................... 5
2.<.1 ?ui@ ?uestions..................................................................................................................... 5
3 Getting Started.................................................................................................................................. 7
3.1 *eAuired %)ills............................................................................................................................ B
3.2 /rogram 0ormats......................................................................................................................... B
3.2.1 /rogram %tatement............................................................................................................... B
3.2.2 :omments............................................................................................................................ B
3.2.3 %imple =utput...................................................................................................................... C
3.2.< E+ample D 0irst /rogram..................................................................................................... C
3.3 Te+t Editor................................................................................................................................... C
3.< :ompiling.................................................................................................................................... C
3.5 E+ecuting..................................................................................................................................... 1
3.E E+ercises...................................................................................................................................... 1
3.E.1 ?ui@ ?uestions..................................................................................................................... 1
3.E.2 %uggested /roFects............................................................................................................. 10
4 Fortran ! " #a$ic %&ement$.......................................................................................................... 11
<.1 Varia(les.................................................................................................................................... 11
<.1.1 Varia(le !ames.................................................................................................................. 11
<.1.2 Ge'words........................................................................................................................... 12
<.2 ;ata T'pes................................................................................................................................. 12
<.2.1 .nteger................................................................................................................................ 12
<.2.2 *eal.................................................................................................................................... 13
<.2.3 :omple+............................................................................................................................. 13
<.2.< :haracter............................................................................................................................ 13
iii
<.2.5 9ogical............................................................................................................................... 13
<.2.E Historical ;ata T'ping....................................................................................................... 13
<.3 ;eclarations............................................................................................................................... 13
<.3.1 ;eclaring Varia(les............................................................................................................ 1<
<.3.2 .nitiali@ation....................................................................................................................... 1<
<.3.3 :onstants........................................................................................................................... 1<
<.< :omments.................................................................................................................................. 15
<.5 :ontinuation 9ines.................................................................................................................... 15
<.5.1 E+ample............................................................................................................................. 15
<.E E+ercises.................................................................................................................................... 1E
<.E.1 ?ui@ ?uestions................................................................................................................... 1E
<.E.2 %uggested /roFects............................................................................................................. 1E
! %'pre$$ion$...................................................................................................................................... 17
5.1 9iterals....................................................................................................................................... 1B
5.1.1 .nteger 9iterals................................................................................................................... 1B
5.1.2 *eal 9iterals....................................................................................................................... 1B
5.1.2.1 E6!otation.................................................................................................................. 1B
5.1.3 :omple+ 9iterals............................................................................................................... 1C
5.1.< :haracter 9iterals............................................................................................................... 1C
5.1.5 9ogical :onstants.............................................................................................................. 1C
5.2 ,rithmetic =perations............................................................................................................... 11
5.2.1 ,ssignment........................................................................................................................ 11
5.2.2 ,ddition............................................................................................................................. 11
5.2.3 %u(traction......................................................................................................................... 11
5.2.< Iultiplication.................................................................................................................... 20
5.2.5 ;ivision............................................................................................................................. 20
5.2.E E+ponentiation................................................................................................................... 20
5.3 /recedence of =perations.......................................................................................................... 21
5.< .ntrinsic 0unctions..................................................................................................................... 21
5.<.1 Iathematical .ntrinsic 0unctions...................................................................................... 21
5.<.2 :onversion 0unctions........................................................................................................ 22
5.<.3 %ummar'............................................................................................................................ 22
5.5 Ii+ed Iode.............................................................................................................................. 23
5.E E+amples................................................................................................................................... 23
5.B E+ercises.................................................................................................................................... 2<
5.B.1 ?ui@ ?uestions................................................................................................................... 2<
5.B.2 %uggested /roFects............................................................................................................. 25
( Simp&e Input and Output............................................................................................................... 27
E.1 =utput D 8rite........................................................................................................................... 2B
E.1.1 =utput D /rint.................................................................................................................... 2C
E.2 .nput D *ead.............................................................................................................................. 2C
E.3 E+ample..................................................................................................................................... 21
E.< E+ercises.................................................................................................................................... 30
E.<.1 ?ui@ ?uestions................................................................................................................... 30
E.<.2 %uggested /roFects............................................................................................................. 30
iv
7 )rogram Deve&opment.................................................................................................................... 33
B.1 "nderstand the /ro(lem............................................................................................................ 33
B.2 :reate the ,lgorithm................................................................................................................. 3<
B.3 ;evelop the /rogram................................................................................................................. 3<
B.< Test5;e(ug the /rogram............................................................................................................ 35
B.<.1 Error Terminolog'............................................................................................................. 35
B.<.1.1 :ompiler Error........................................................................................................... 35
B.<.1.2 *un6time Error........................................................................................................... 3E
B.<.1.3 9ogic Error................................................................................................................. 3B
B.5 E+ercises.................................................................................................................................... 3B
B.5.1 ?ui@ ?uestions................................................................................................................... 3B
B.5.2 %uggested /roFects............................................................................................................. 3C
* Se&ection Statement$....................................................................................................................... 3
C.1 *elational E+pressions.............................................................................................................. 31
C.2 9ogical =perators...................................................................................................................... <0
C.3 .0 %tatements............................................................................................................................. <0
C.3.1 .0 THE! %tatement........................................................................................................... <1
C.3.1.1 .0 THE! %tatement, %imple 0orm............................................................................ <1
C.3.2 .0 THE! E9%E %tatement................................................................................................. <1
C.3.3 .0 THE! E9%E .0 %tatement............................................................................................ <2
C.< E+ample =ne............................................................................................................................. <3
C.<.1 "nderstand the /ro(lem.................................................................................................... <3
C.<.2 :reate the ,lgorithm.......................................................................................................... <<
C.<.3 ;evelop the /rogram......................................................................................................... <5
C.<.< Test5;e(ug the /rogram.................................................................................................... <E
C.5 %E9E:T :,%E %tatement........................................................................................................ <E
C.E E+ample Two............................................................................................................................. <1
C.E.1 "nderstand the /ro(lem.................................................................................................... <1
C.E.2 :reate the ,lgorithm.......................................................................................................... <1
C.E.3 ;evelop the /rogram......................................................................................................... <1
C.E.< Test5;e(ug the /rogram.................................................................................................... 50
C.B E+ercises.................................................................................................................................... 51
C.B.1 ?ui@ ?uestions................................................................................................................... 51
C.B.2 %uggested /roFects............................................................................................................. 52
+ooping............................................................................................................................................ !!
1.1 :ounter :ontrolled 9ooping..................................................................................................... 55
1.2 EJ.T and :#:9E %tatements................................................................................................... 5B
1.3 :ounter :ontrolled E+ample..................................................................................................... 5B
1.3.1 "nderstand the /ro(lem.................................................................................................... 5B
1.3.2 :reate the ,lgorithm.......................................................................................................... 5C
1.3.3 ;evelop the /rogram......................................................................................................... 5C
1.3.< Test5;e(ug the /rogram.................................................................................................... 51
1.< :onditional :ontrolled 9ooping............................................................................................... 51
1.5 :onditionall' :ontrolled 9oop E+ample.................................................................................. E0
1.5.1 "nderstand the /ro(lem.................................................................................................... E0
v
1.5.2 :reate the ,lgorithm.......................................................................................................... E0
1.5.3 ;evelop the /rogram......................................................................................................... E1
1.5.< Test5;e(ug the /rogram.................................................................................................... E2
1.E E+ercises.................................................................................................................................... E2
1.E.1 ?ui@ ?uestions................................................................................................................... E2
1.E.2 %uggested /roFects............................................................................................................. E3
1, Formatted Input-Output.............................................................................................................. (!
10.1 0ormat..................................................................................................................................... E5
10.2 0ormat %pecifiers.................................................................................................................... E5
10.3 .nteger 0ormat %pecifier.......................................................................................................... EE
10.< *eal 0ormat %pecifier.............................................................................................................. EB
10.5 9ogical 0ormat %pecifier......................................................................................................... EB
10.E :haracter 0ormat %pecifier..................................................................................................... EC
10.B ,dvance :lause....................................................................................................................... EC
10.C E+ample................................................................................................................................... E1
10.C.1 "nderstand the /ro(lem.................................................................................................. E1
10.C.2 :reate the ,lgorithm........................................................................................................ B0
10.C.3 ;evelop the /rogram....................................................................................................... B0
10.C.< Test5;e(ug the /rogram.................................................................................................. B2
10.1 E+ercises.................................................................................................................................. B2
10.1.1 ?ui@ ?uestions................................................................................................................. B2
10.1.2 %uggested /roFects........................................................................................................... B3
11 Character$ and String$................................................................................................................. 7!
11.1 :haracter and %tring :onstants............................................................................................... B5
11.2 :haracter Varia(le ;eclaration................................................................................................ B5
11.3 :haracter Varia(le .nitiali@ation.............................................................................................. BE
11.< :haracter :onstants................................................................................................................. BE
11.5 :haracter ,ssignment.............................................................................................................. BB
11.E :haracter =perators................................................................................................................. BB
11.B :haracter %u(strings................................................................................................................ BB
11.C :haracter :omparisons........................................................................................................... BC
11.1 .ntrinsic :haracter =perations................................................................................................. BC
11.10 E+ample................................................................................................................................. B1
11.10.1 "nderstand the /ro(lem................................................................................................. B1
11.10.2 :reate the ,lgorithm...................................................................................................... B1
11.10.3 ;evelop the /rogram..................................................................................................... B1
11.10.< Test5;e(ug the /rogram................................................................................................ C0
11.11 E+ercises................................................................................................................................ C1
11.11.1 ?ui@ ?uestions............................................................................................................... C1
11.11.2 %uggested /roFects......................................................................................................... C1
12 Fi&e Operation$.............................................................................................................................. *3
12.1 0ile =pen................................................................................................................................. C3
12.2 0ile 8rite................................................................................................................................. C<
12.3 0ile *ead.................................................................................................................................. C<
vi
12.< *ewind..................................................................................................................................... C5
12.5 >ac)space................................................................................................................................ C5
12.E :lose 0ile................................................................................................................................. CE
12.B E+ample................................................................................................................................... CE
12.B.1 "nderstand the /ro(lem.................................................................................................. CE
12.B.2 :reate the ,lgorithm........................................................................................................ CE
12.B.3 ;evelop the /rogram....................................................................................................... CB
12.B.< Test5;e(ug the /rogram.................................................................................................. CC
12.C E+ercises.................................................................................................................................. CC
12.C.1 ?ui@ ?uestions................................................................................................................. C1
12.C.2 %uggested /roFects........................................................................................................... C1
13 Sing&e Dimen$ion .rray$.............................................................................................................. 1
13.1 ,rra' ;eclaration.................................................................................................................... 11
13.1.1 %tatic ;eclaration............................................................................................................. 11
13.1.2 %tatic ,rra' ;eclaration.................................................................................................. 12
13.1.3 ;'namic ,rra' ;eclaration............................................................................................. 12
13.1.3.1 ;'namic ,rra' ,llocation....................................................................................... 13
13.2 ,ccessing ,rra' Elements....................................................................................................... 13
13.3 .mplied ;o69oop..................................................................................................................... 1<
13.< .nitiali@ing ,rra's.................................................................................................................... 1<
13.5 E+ample................................................................................................................................... 15
13.5.1 "nderstand the /ro(lem.................................................................................................. 15
13.5.2 :reate the ,lgorithm........................................................................................................ 15
13.5.3 ;evelop the /rogram....................................................................................................... 1B
13.5.< Test5;e(ug the /rogram.................................................................................................. 11
13.E ,rra's of %trings...................................................................................................................... 11
13.B E+ercises.................................................................................................................................. 11
13.B.1 ?ui@ ?uestions................................................................................................................. 11
13.B.2 %uggested /roFects......................................................................................................... 101
14 /u&tidimen$iona& .rray$............................................................................................................ 1,3
1<.1 ,rra' ;eclaration.................................................................................................................. 103
1<.1.1 %tatic ;eclaration........................................................................................................... 10<
1<.1.2 ;'namic ;eclaration..................................................................................................... 10<
1<.1.3 ;'namic ,rra' ,llocation............................................................................................. 10<
1<.2 ,ccessing ,rra' Elements..................................................................................................... 105
1<.3 E+ample................................................................................................................................. 10E
1<.3.1 "nderstand the /ro(lem................................................................................................ 10E
1<.3.2 :reate the ,lgorithm...................................................................................................... 10B
1<.3.3 ;evelop the /rogram..................................................................................................... 10C
1<.3.< Test5;e(ug the /rogram................................................................................................ 101
1<.< E+ercises................................................................................................................................ 101
1<.<.1 ?ui@ ?uestions............................................................................................................... 101
1<.<.2 %uggested /roFects......................................................................................................... 110
1! Su0program$................................................................................................................................ 113
vii
15.1 %u(program T'pes................................................................................................................. 113
15.2 /rogram 9a'out..................................................................................................................... 113
15.2.1 .nternal *outines............................................................................................................ 11<
15.2.2 E+ternal *outines........................................................................................................... 11<
15.3 ,rguments.............................................................................................................................. 11<
15.3.1 ,rgument .ntent............................................................................................................. 11<
15.< Varia(le %cope....................................................................................................................... 11<
15.5 "sing 0unctions and %u(routines.......................................................................................... 11<
15.5.1 ,rgument /assing.......................................................................................................... 115
15.E 0unctions............................................................................................................................... 115
15.E.1 .ntrinsic 0unctions......................................................................................................... 115
15.E.2 "ser6;efined 0unctions................................................................................................. 115
15.E.2.1 %ide Effects............................................................................................................ 11E
15.B %u(routines............................................................................................................................ 11E
15.C E+ample................................................................................................................................. 11C
15.C.1 "nderstand the /ro(lem................................................................................................. 111
15.C.2 :reate the ,lgorithm...................................................................................................... 120
15.C.3 ;evelop the /rogram..................................................................................................... 120
15.C.< Test5;e(ug the /rogram................................................................................................ 122
15.1 E+ercises................................................................................................................................ 122
15.1.1 ?ui@ ?uestions............................................................................................................... 122
15.1.2 %uggested /roFects......................................................................................................... 122
1( Derived Data 1ype$..................................................................................................................... 12!
1E.1 ;efinition............................................................................................................................... 125
1E.2 ;eclaration............................................................................................................................ 12E
1E.3 ,ccessing :omponents.......................................................................................................... 12E
1E.< E+ample =ne......................................................................................................................... 12B
1E.<.1 "nderstand the /ro(lem................................................................................................ 12B
1E.<.2 :reate the ,lgorithm...................................................................................................... 12C
1E.<.3 ;evelop the /rogram..................................................................................................... 12C
1E.<.< Test5;e(ug the /rogram................................................................................................ 130
1E.5 ,rra's of ;erived ;ata.......................................................................................................... 130
1E.E E+ample Two......................................................................................................................... 132
1E.E.1 "nderstand the /ro(lem................................................................................................ 132
1E.E.2 :reate the ,lgorithm...................................................................................................... 132
1E.E.3 ;evelop the /rogram..................................................................................................... 133
1E.E.< Test5;e(ug the /rogram................................................................................................ 13E
1E.B E+ercises................................................................................................................................ 13E
1E.B.1 ?ui@ ?uestions............................................................................................................... 13E
1E.B.2 %uggested /roFects......................................................................................................... 13B
17 /odu&e$........................................................................................................................................ 13
1B.1 Iodule ;eclaration............................................................................................................... 131
1B.2 "se %tatement........................................................................................................................ 1<0
1B.3 "pdated :ompilation :ommands......................................................................................... 1<0
1B.< Iodule E+ample /rogram..................................................................................................... 1<1
viii
1B.<.1 "nderstand the /ro(lem................................................................................................ 1<1
1B.<.2 :reate the ,lgorithm...................................................................................................... 1<1
1B.<.3 ;evelop the /rogram..................................................................................................... 1<2
1B.<.3.1 Iain /rogram........................................................................................................ 1<2
1B.<.3.2 Iodule *outines.................................................................................................... 1<3
1B.<.< Test5;e(ug the /rogram................................................................................................ 1<<
1B.5 E+ercises................................................................................................................................ 1<<
1B.5.1 ?ui@ ?uestions............................................................................................................... 1<<
1B.5.2 %uggested /roFects......................................................................................................... 1<<
1* .ppendi' . " .SCII 1a0&e.......................................................................................................... 14!
1 .ppendi' # " 2indo3$ Start45p In$truction$......................................................................... 147
11.1 8or)ing 0iles........................................................................................................................ 1<B
11.2 =(taining The :ompiler........................................................................................................ 1<B
11.3 :ommand /rompt.................................................................................................................. 1<C
11.3.1 8indows J/5Vista5B...................................................................................................... 1<C
11.3.2 8indows C..................................................................................................................... 1<C
11.3.3 :ommand /rompt 8indow........................................................................................... 1<C
11.3.< ;evice and ;irector'..................................................................................................... 1<C
11.< :ompiler .nstallation Verification......................................................................................... 1<1
11.5 :ompilation........................................................................................................................... 1<1
11.E E+ecuting............................................................................................................................... 150
11.B E+ample................................................................................................................................. 150
2, .ppendi' C " 6andom 7um0er Generation............................................................................ 1!1
20.1 .nitiali@ation........................................................................................................................... 151
20.2 enerating *andom !um(er................................................................................................. 151
20.3 E+ample................................................................................................................................. 152
20.< E+ample................................................................................................................................. 152
21 .ppendi' D " Intrin$ic Function$.............................................................................................. 1!!
21.1 :onversion 0unctions............................................................................................................ 155
21.2 .nteger 0unctions................................................................................................................... 155
21.3 *eal 0unctions....................................................................................................................... 15E
21.< :haracter 0unctions............................................................................................................... 15E
21.5 :omple+ 0unctions................................................................................................................ 15B
21.E ,rra' 0unctions..................................................................................................................... 15B
21.B %'stem .nformation 0unctions.............................................................................................. 15C
22 .ppendi' % " 8i$ua&ization 3ith G75p&ot............................................................................... 1!
22.1 =(taining !"plot............................................................................................................... 151
22.2 0ormatting /lot 0iles............................................................................................................. 151
22.2.1 Header............................................................................................................................ 1E0
22.2.2 0ooter............................................................................................................................. 1E0
22.3 /lotting 0iles.......................................................................................................................... 1E0
22.< E+ample................................................................................................................................. 1E0
i+
22.<.1 /lot /rogram.................................................................................................................. 1E1
22.<.2 /lot 0ile.......................................................................................................................... 1E2
22.<.3 /lot =utput..................................................................................................................... 1E2
23 .ppendi' F " Fortran ! 9ey3ord$.......................................................................................... 1(3
Inde'................................................................................................................................................... 1(7
Illustration Index
.llustration 1$ :omputer ,rchitecture..............................................................................................3
.llustration 2$ 0ortran 15 :ompile /rocess......................................................................................<
+
1 Introduction
:omputers are ever'where in our dail' lives. 0rom the des)top, laptop, phone, (an), and vehicle, it is
difficult to completel' get awa' from computers. .t onl' ma)es sense to learn a little a(out how a
computer reall' wor)s.
This te+t provides an introduction to programming and pro(lem solving using the 0ortran 15
programming language. This introduction is geared for non computer science maFors. ,s such, this
te+t is not a complete, comprehensive guide to the 0ortran 15 programming language. The primar'
focus is on an introduction to pro(lem solving and algorithm development. ,s such, man' details of
the 0ortran 15 language are omitted.
1.1 Why Learn Programming
0or science and technical maFors, computers are used e+tensivel' in all aspects of a each discipline.
9earning the (asics of how computers wor) and how programs are created is useful and directl'
applica(le.
/rogramming a computer is (asicall' applied pro(lem solving. #ou are given a pro(lem, the pro(lem
is anal'@ed, a solution developed, then that solution is implemented and tested. Enhanced pro(lem
solving s)ills can (e applied to an' endeavor. These (asic s)ills, once developed, can (e applied to
other programming languages, I,T9,>, or even spreadsheet macro7s.
"nfortunatel', learning programing and how a computer reall' wor)s ma' ruin some > movies.
1. Fortran
0ortran is a programming language often used (' the scientific communit'. .ts name is a contraction of
0=*mula T*,!slation. 0=*T*,! is one of the earliest programming languages.
This te+t utili@es the 0ortran 10515 standard. =lder versions of 0ortran, li)e 0ortran BB, are not
referenced. The older 0ortran versions have less features and reAuire additional, often (urdensome
formatting reAuirements.
1.! Com"lete Fortran 95 #ocumentation
This te+t it is not a comprehensive or complete reference to the 0ortran 15 language. The entire !"
0ortran compiler documentation is availa(le on6line at the following location$
http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gfortran/
.f this location changes, a we( search will (e a(le to find the new location.
1
:hapter 1 K .ntroduction
1.$ What Is % Program
, computer program is a series of instructions which ena(les the computer to perform a designated
tas). ,s this te+t will demonstrate, a computer must (e told what to do in precise, step6('6step detail.
These steps might include o(taining data, arithmetic operations 3additional, su(traction, multiplication,
division, etc.4, data storage, and information output. The computer will perform these tas)s as
instructed, even if the' don7t alwa's ma)e sense. :onseAuentl', it is the programmer who must
develop a solution to the pro(lem.
1.5 &"erating 'ystem
The =perating %'stem, or =%, is an interface (etween the user and the hardware 3:/", memor',
screen, dis) drive, etc.4. The =% is responsi(le for the management of the hardware, coordination of
activities and the sharing of the resources of the computer that acts as a host for computing applications
run on the machine. The common operating s'stems include various versions of 8indows. I,: =%
J, and "!.J59inu+. /rograms written in 0ortran will wor) on these operating s'stems.
2
Com"uter &rgani(ation
>efore writing programs, it is useful to understand some (asics a(out how a computer is organi@ed.
This section provides a (rief, high6level overview of the (asic components of a computer and how it is
organi@ed.
.1 %rchitecture &)er)ie*
The (asic components of a computer include a :entral /rocessing "nit 3:/"4, *andom ,ccess
Iemor' 3*,I4, ;is) ;rive, and .nput5=utput devices 3i.e., screen and )e'(oard4, and an
interconnection referred to as >"%.
, ver' (asic diagram of a computer architecture is as follows$
/rograms and data are t'picall' stored on the dis) drive. 8hen a program is e+ecuted, it must (e
copied from the dis) drive into the *,I memor'. The :/" e+ecutes the program from *,I. This is
similar to storing a term paper on the dis) drive, and when writing5editing the term paper, it is copied
from the dis) drive into memor'. 8hen done, the updated version is stored (ac) to the dis) drive.
3
Illustration 1: Computer Architecture
Screen / Keyboard /
Mouse
Disk Drive /
Other Storage Media
Random Access
Memory (RAM)
CP
!S
("nterconnection)
:hapter 2 K :omputer =rgani@ation
. Com"iler
/rograms are written in the 0ortran programming language. However, the :/" does not read 0ortran
directl'. .nstead, the 0ortran program that we create will (e converted into (inar' 317s and 07s4 (' the
compiler. The :/" will read the instructions and information, represented in (inar', and perform the
commands from the program.
The compiler is a program itself and is reAuired in order to create the files needed to e+ecute programs
written in 0ortran 15.
.! Information +e"resentation
,ll information, including num(ers, characters, and instructions are represented in the computer in
(inar' 317s and 07s4. The information is converted into (inar' representation 317s and 07s4 for storage in
the computer. 0ortunatel', this is generall' done transparentl'.
2.3.1 Decimal Numbers
>efore discussing (inar' num(ers, a (rief review of the decimal s'stem is presented. The num(er
L123<L as,
Thousands Hundreds Tens =nes
10
3
10
2
10
1
10
0
1000 100 10 1
1 2 3 <
8hich means,
123< = 11000 2100 310 <1
123< = 110
3
210
2
310
1
<10
0
The decimal s'stem is base 10 using the digits 0 through 1.
<
Illustration 2: Fortran 95 Compile Process
#ortran $% Com&i'er ()ecutab'e
Program #i'e
:hapter 2 M :omputer =rgani@ation
2.3.2 Binary Numbers
The (inar' s'stem, as well as its math, operates in base 2, using two s'm(ols, 0 and 1.
2
B
2
E
2
5
2
<
2
3
2
2
2
1
2
0
12C E< 32 1E C < 2 1
0 0 0 0 1 1 0 1
.n (ase 2, we put the digits 061 in columns 2
0
, 2
1
, 2
3
, and so on. 0or e+ample,
1101
2
= 12
3
12
2
02
1
12
0
= C<1
8hich is decimal is 13
10
.
2.3.3 Character Representation
:haracters are represented using the ,merican %tandard :ode for .nformation .nterchange 3,%:..4.
*efer to ,ppendi+ ,.
.$ ,xercises
>elow are some Aui@ Auestions (ased on this chapter.
2.4.1 Quiz Questions
>elow are some Aui@ Auestions.
14 How is information represented in the computerN
24 8hat does the 0ortran compiler doN
34 8hat architecture component connects the memor' to the :/"N
<4 8hat is 0000101
2
in decimalN
54 How are characters represented in the computerN
E4 8here are programs stored when the computer is turned offN
B4 8here must programs (e located when the' are e+ecutingN
5
:hapter 2 K :omputer =rgani@ation
E
! -etting 'tarted
This section provides a (rief overview of how to get started. This includes the general process for
creating a ver' simple program, compiling, and e+ecuting the program. %ome detailed steps regarding
wor)ing with files, o(taining the compiler, and compiling a program are included in Appendix B
!indo"s #tart$up Instructions.
!.1 +e.uired '/ills
>efore starting, 'ou should have some (asic computer s)ills, including the following$
,(ilit' to use a we( (rowser
>asic understanding of computer director' structure
0ile manipulation 3create, delete, rename, move, etc.4
,(ilit' to edit a te+t file
.ncludes selecting and learning a te+t editor 3i.e., !otepad, !otepadOO, emacs, etc.4
.f 'ou are unsure a(out an' or all of these reAuirements 'ou will need to learn them. 0ortunatel', the'
are not difficult. ,dditionall', there are numerous tutorials availa(le on the 8e(.
The following sections assume the the 0ortran 15 compiler is installed and availa(le. 0or additional
information regarding o(taining and installing the compiler, refer to ,ppendi+ >. The 0ortran 15
compiler is availa(le for download at no cost.
!. Program Formats
0ortran 15 programs must (e written and formatted in a specific manner. The following sections
summari@e the (asic program elements followed (' a simple e+ample.
3.2.1 Program tatement
, 0ortran 15 program is started with a program statement, 7program <name>7, and ended with an end
program statement, 7end program <name>7. *efer to the e+ample first program to see an e+ample of
these statements.
3.2.2 Comments
:omments are information for the programmer and are not read (' the computer. 0or e+ample,
comments t'picall' include information a(out the program. 0or programming assignments, the
comments should include the programmer name, assignment num(er, and a (rief description of the
program.
B
:hapter 3 K etting %tarted
3.2.3 imple !utput
, program can displa' a simple message to the screen (' using the "rite statement. 0or e+ample$
write(*,*) "Hello World"
8ill displa' the message Hello World to the screen. ,dditional information regarding the write
statement and outputting information is provided in later chapters.
3.2.4 "#ample $ %irst Program
The following trivial program illustrates the initial formatting reAuirements.
! Simple Example Program
program first
write (*,*) "Hello World"
end program first
.n this e+ample, the program is named 7first7. This file is t'picall' referred to as the source file.
!.! Text ,ditor
The first step is to create a te+t file named hw.f95 using a te+t editor. .t is useful to place programs
and various files into a wor)ing director'. This wa' the files can (e easil' found and not confused with
other, unrelated files and data. The hw.f95 file should (e created and placed in the wor)ing
director'.
, file name is t'picall' comprised of two partsP a name and an e+tension. .n this e+ample, the name is
hw and the e+tension is .f95. The usual e+tension for this a future programs will (e .f95 which
indicates that the file is a 0ortran 15 source file.
The following e+amples will use the hw.f95 file name. .f desired, a different file name ma' (e
used. However, the name will need to (e adFusted for the compiler and e+ecute steps.
!.$ Com"iling
=nce the program is t'ped into a file, the file must (e compiled. :ompiling will convert the human
reada(le 0ortran program, or source file, into a computer reada(le version 3in (inar'4.
.n the e+amples (elow, the commands t'ped (' the user are displa'ed in (old. The regular 3non6
(olded4 te+t refers to prompts or other information displa'ed (' the computer 3which will not need to
(e t'ped4.
To compile the e+ample program, the following command would (e entered$
K:\mydir> gfortran -o hw hw.f95
This command will tell the 7gfortran7 compiler to read the file hw.f95 and, if there are no errors,
C
:hapter 3 M etting %tarted
create an e+ecuta(le file named hw.exe. .f there is an error, the compiler will generate an error
message, sometimes cr'ptic, and provide a line num(er. %uch errors are usuall' the result of mist'ping
one of the instructions. ,n' errors must (e resolve (efore continuing.
!.5 ,xecuting
To e+ecute or run a program, t'pe the name of the e+ecuta(le file. 0or e+ample, to e+ecute or run the
hw.exe program$
K:\mydir> hw
Hello World
K:\mydir>
8hich will e+ecute the e+ample program and displa' the -Hello 8orld2 message to the screen. , more
complete e+ample is as follows$
.t is not necessar' to t'pe the e+tension 3i.e., -.e+e24 portion of the file name.
!.0 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
3.&.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat the the input file for the compilerN
24 8hat is the output file from the compilerN
34 0ortran program must start with and end with what statementN
1
:hapter 3 K etting %tarted
<4 How are 0ortran 15 comments mar)edN
54 8hat is the t'pical 0ortran 15 source file e+tensionN
E4 8hat is the t'pical 0ortran 15 compiler output file e+tension 3after the program is compiled4N
3.&.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 :reate a wor)ing director' for the storage of program files 3on the computer (eing used4.
24 =(tain and install the !" 0ortran 15 compiler on a suita(le computer. *efer to ,ppendi+ >
as needed.
34 T'pe in the hello world program, compile, and e+ecute the program.
<4 "pdate the e+ample program to displa' 'our name in addition to the Hello 8orld message.
10
$ Fortran 95 1 2asic ,lements
>efore (eginning to writing programs, it is necessar' to )now some of the (asic elements of the
0ortran language. This section descri(es some of the (asic elements of 0ortran. ,dditional
information will (e added in later sections.
$.1 3ariables
The (asic concept in a program is the concept of a varia(le. Varia(les in a program are li)e varia(les in
an alge(raic e+pression. The' are used to hold values and then write mathematical e+pressions using
them. 0ortran allows us to have varia(les of different t'pes.
, varia(le can hold one value at a time. .f another value is placed in the varia(le, the previous value is
over6written and lost.
Varia(le !ame Q <2
Varia(les must (e declared at the start of the program (efore the' are used.
4.1.1 )ariable Names
Each varia(le must (e named. The varia(le name is how varia(les, which are memor' locations, are
referred to (' the program. , varia(le name must start with a letter, followed (' letters, num(ers, or an
underscore 3-R24 and ma' not (e longer than 32 characters. :apital letters are treated the same wa' as
lower6case letters, 3i.e., -,,,2 is the same varia(le as -aaa24.
0or e+ample, some valid varia(le names are as follows$
x
today
next_month
summation1
%ome invalid e+amples include$
1today
this_is_a_variable_name_with_way_way_to_many_characters_in_it
next@month
next month
today!
!ote that the space 3(etween ne+t and month4 or the special character, S, is not allowed. ,dditionall',
each varia(le must have a t'pe associated as e+plained in the following sections.
11
:hapter < K 0ortran 15 D >asic Elements
4.1.2 *ey+or's
.n programming, a )e'word is a word or identifier that has a special 0ortran meaning. 0or e+ample, in
the -hello world2 program from the previous chapter, the word program had a special meaning in that it
used to note the start or (eginning of a program. ,dditionall', the word "rite has a special meaning to
note an output action 3e.g., writing some information to an output device, li)e the screen4.
%uch )e'words are reserved in that the' can not (e used for an'thing else such varia(le names. That is,
a varia(le name of program or write is not allowed.
,s additional 0ortran 15 statements and language constructs are e+plained, more )e'words will
identified. .n general, words used for 0ortran language statements, attri(utes, and constructs will li)el'
(e )e'words. , complete list of )e'words or reserved words is located in ,ppendi+ 0.
$. #ata Ty"es
0ortran, li)e man' other high level programming languages, supports several different data t%pes to
ma)e data manipulation easier. The most freAuentl' used data t'pes are integer and floating point.
=ther data t'pes are comple+ num(ers, characters and logical data.
.n a 0ortran statement, data can appear either as a literal 3e.g., an actual value such as 3.1<151, 1E,
65.<e6<4 or as a varia(le name which identifies a location in memor' to store the data.
The five (asic 0ortran 15 data t'pes are as follows$
1ype De$cription
integer Varia(le that is an integer or whole num(er 3not a
fraction4 that can (e positive, negative, or @ero.
rea& Varia(le that can set set to a real num(er.
comp&e' Varia(le that can (e set to a comple+ num(er.
character Varia(le that is a character or seAuence of
characters.
&ogica& Varia(le that can onl' (e set to .true. or .false.
.t is also possi(le to have derived t'pes and pointers. >oth of these can (e useful for more advanced
programs and are descri(ed in later chapters.
4.2.1 ,nteger
,n integer
1
is a whole num(er 3not a fraction4 that can (e positive, negative, or @ero. E+amples include
the num(ers 10, 0, 625, and 5,1<C. .ntegers are the num(ers people are most familiar with, and the'
serve a crucial role in mathematics and computers. ,ll integers are whole num(ers, so operations li)e
one divided (' two 31524 is 0 since the result must (e a whole num(er. 0or integer division, no
rounding will occur as the fractional part is truncated.
1 0or more information regarding integers, refer to$ http$55en.wi)ipedia.org5wi)i5.nteger
12
:hapter < M 0ortran 15 D >asic Elements
4.2.2 Real
, real num(er
2
includes the fractional part, even if the fractional part is 0. *eal num(ers, also referred
to as floating point num(ers, include (oth rational num(ers and irrational num(ers. E+amples of
irrational num(ers or repeating decimals include T,
2 and e. ,dditional e+amples include 1.5, 5.0,
and 3.1<151. 0ortran 15 will accept 5. as 5.0. ,ll e+amples in this te+t will include the -.02 to ensure
clarit'.
4.2.3 Comple#
, comple+ num(er
3
, in mathematics, is a num(er comprising a real num(er and an imaginar' num(er. .t
can (e written in the form of a O bi, where a and b are real num(ers, and the i is the standard imaginar'
unit with the propert' that i
2
U V1.0. The comple+ num(ers contain the ordinar' real num(ers, (ut
e+tend them (' adding in e+tra num(ers li)e an e+tra dimension. This data t'pe is not used
e+tensivel', (ut can (e useful when needed.
4.2.4 Character
, character
<
is a s'm(ol li)e a letter, numerical digit, or punctuation. , string
5
is a seAuence or set of
characters. :haracters and strings are t'picall' enclosed in Auotes. 0or e+ample, the upper case letter
-W2 is a character and -Hello 8orld2 is a string. The characters are represented in a standardi@ed
format referred to as ,%:...
4.2.- .ogical
, logical
E
is is onl' allowed to have two values, true or false. , logical is can also (e referred to as a
(oolean. The true and false values are e+pressed as .true. or .:a&$e. which are called logical constants.
The leading and trailing . 3period4 is reAuired for the true and false constants.
4.2.& /istorical Data 0yping
"nless a varia(le was e+plicitl' t'ped, older versions of 0ortran implicitl' assumed a t'pe for a
varia(le depending on the first letter of its name. Thus, if not e+plicitl' declared, a varia(le whose
name started with one of the letters I through O was assumed to (e an integerP otherwise it was
assumed to (e real. To allow older code to run, 0ortran 15 permits implicit t%ping. However, this is
poor practice and often leads to errors. %o, we will include the .I/9.:.T !=!E statement at the start
of all programs. This turns off implicit t'ping and the compiler will identif' an' varia(le not defined.
$.! #eclarations
0ortran varia(les must (e declared (efore an' e+ecuta(le statements. This section provides an
introduction to how varia(les are declared.
2 0or more information regarding real num(ers, refer to$ http$55en.wi)ipedia.org5wi)i5*ealRnum(ers
3 0or more information regarding comple+ num(ers, refer to$ http$55en.wi)ipedia.org5wi)i5*ealRnum(ers
< 0or more information regarding characters, refer to$ http$55en.wi)ipedia.org5wi)i5:haracterR3computing4
5 0or more infromation regarding strings, refer to$ http$55en.wi)ipedia.org5wi)i5%tringR3computerRscience4
E 0or more information regarding logicals, refer to$ http$55en.wi)ipedia.org5wi)i5>ooleanRdataRt'pe
13
:hapter < K 0ortran 15 D >asic Elements
4.3.1 Declaring )ariables
;eclaring varia(les formall' defines the data t'pe of each varia(le and sets aside a memor' location.
This is performed (' a t'pe declaration statement in the form of$
<type> :: <list of variable names>
The t'pe must (e one of the predefined data t'pes 3integer, real, comple+, character, logical4. =utlined
in the previous section. ;eclarations are placed in the (eginning of the program 3after the program
statement4.
0or e+ample, to define an integer varia(le toda%,
integer :: today
,dditional e+amples include$
integer :: today, tomorrow, yesterday
real :: ans2
complex :: z
logical :: answer
The declarations can (e entered in an' order.
,dditional information regarding character varia(les is provided in a later chapter.
4.3.2 ,nitialization
.t is possi(le to declare a varia(le and to set it is initial value at the same time. This initiali@ation is not
reAuired, (ut can sometime (e convenient. 0or e+ample, to define an integer varia(le toda%sdate and
set it to the 15
th
of the month$
integer :: todaysdate=15
,dditional e+amples include$
integer :: todaysday=15, tomorrow=16, yesterday=14
real :: ave = 5.5
%paces or no spaces (etween the varia(les, eAual signs, semicolons, and commas are allowed.
Varia(les initiali@ed at declaration can (e changed later in the program as needed.
4.3.3 Constants
, constant is a varia(le that can not (e changed during program e+ecution. 0or e+ample, a program
might declare a varia(le for ; and set it to 3.1<151. .t is unli)el' that a program would need to change
the value for the value for ;. The parameter Aualifier will set varia(le as a constant which sets the
initial values and does not allow that initial value to (e altered.
1<
:hapter < M 0ortran 15 D >asic Elements
0or e+ample, the declarations$
real, parameter :: pi = 3.14159
integer, parameter :: width = 1280
will set the varia(le pi to 3.1<151 and width to 12C0 ensure that the' can not (e changed while thr
program is e+ecuting.
$.$ Comments
:omments are information for the programmer and are not read (' the :/". 0or e+ample, comments
t'picall' include information a(out the program. 0or programming assignments, the comments should
include the programmer name, assignment num(er, and a description of the program.
$.5 Continuation Lines
, statement must start on a new line. .f a statement is too long to fit on a line, it can (e continued on
the ne+t line with an ampersand 37X74. Even shorter lines can (e split and continued on multiple lines
for more reada(le formatting. 0or e+ample,
A = 174.5 * year &
+ count / 100.0
.s eAuivalent to the following
A = 174.5 * year + count / 100.0
!ote that the 7X7 is not part of the statement.
4.-.1 "#ample
The following trivial program illustrates the program formatting reAuirements and varia(le
declarations.
! Example Program
program example1
implicit none
integer :: radius, diameter
integer :: height=100, width=150
real :: area, perimeter
real :: length = 123.5, distance=413.761
real, parameter :: pi = 3.14159
write (*,*) "Hello World"
end program example1
.n this e+ample, a series of varia(les are defined 3as e+amples4 (ut not used. The following chapters
will address how to use the varia(les to perform calculations and displa' results.
15
:hapter < K 0ortran 15 D >asic Elements
$.0 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
4.&.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat are the five 0ortran 15 data t'pesN
24 8hat should a 0ortran varia(le name start withN
34 8hat data t'pe are each of the following num(ers 3integer or real4N
<B5 RRRRRRRRRRRR
11.25 RRRRRRRRRRRR
11123 RRRRRRRRRRRR
5.0 RRRRRRRRRRRR
123.<5E RRRRRRRRRRRR
<4 8rite the statements reAuired to declare value as an integer and count as a real.
54 8rite the statements reAuired to declare rate as an real initiali@ed to B.5.
E4 8rite the statements reAuired to declare e as an real constant initiali@ed to 2.B1C2C1C3.
4.&.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the example1 e+ample program, compile, and e+ecute the program.
1E
5 ,x"ressions
This section descri(es how to form (asic 0ortran 15 e+pressions and perform arithmetic operations
3i.e., add, su(tract, multiple, divide, etc.4. E+pressions are formed using literals 3actual values4,
varia(les, and operators 3i.e., <, 4, =, -, etc.4. The previous chapter provides an e+planation of what
varia(le is and a summar' of the five 0ortran data t'pes.
5.1 Literals
The simplest e+pression is a direct value, referred to as a literal. %ince literals are actual values, not
varia(les, the' can not (e changed. There are various t'pes of literal constants descri(ed in the
following sections, correspond to the data t'pes.
-.1.1 ,nteger .iterals
The following are some e+amples of integer constants$
1
0
-100
32767
+42
,n integer must (e a whole num(er 3with no factional component4.
-.1.2 Real .iterals
The following are some e+amples of real constants$
1.0
-0.25
3.14159
The real num(er should include the decimal point 3i.e., the -.24. , real num(er includes the fractional
part, even if the fraction is 0. 0ortran will accept a num(er with the -.2 and no further digits. 0or e+ample,
5. is the same as 5.0. ,ll e+amples in this te+t will include the -.02 to ensure clarit'.
-.1.2.1 "1Notation
0or larger real num(ers, e$notation ma' (e useful. The e6notation means that 'ou should multipl' the
constant (' 10 raised to the power following the LEL. This is sometimes referred to as scientific
notation.
1B
:hapter 5 K E+pressions
The following are some real constants using e6notation$
2.75E6
3.3333E-1
Hence, 2.B5E5 is 2.B510
5
or 2B5,000 and 3.333E61 is 3.33310
1
or 0.3333 or appro+imatel'
one third.
-.1.3 Comple# .iterals
, complex constant is designated (' a pair of constants 3integer or real4, separated (' a comma and
enclosed in parentheses. E+amples are$
(3.2, -4.1)
(1.0, 9.9E-1)
The first num(er denotes the real part and the second the imaginar' part. 8hile a comple+ num(er
consits of two elements it is considered a single value.
-.1.4 Character .iterals
, character constant is either a single character or a set of characters, called a string. , character is a
single character enclosed in Auotes. , string consists of an ar(itrar' seAuence of characters also
enclosed in Auotes. %ome e+amples include$
"X"
"Hello World"
"Good bye cruel world!"
"Have a nice day"
:haracter and string constants 3enclosed with Auotes4 are case sensitive. %o, character -J2 3upper6
case4 is not the same as -+2 3lower6case4.
, pro(lem arises if 'ou want to have a Auote in the string itself. , dou(le Auote will (e interpreted as a
single within a string.
"He said ""wow"" when he heard"
The dou(le6Auoting is sometimes referred to as an escape character. %trings and characters must (e
associated with the character data t'pe.
-.1.- .ogical Constants
The fifth t'pe is logical constant. These can onl' have one of two values$
.true.
.false.
The dots enclosing the true and false are reAuired.
1C
:hapter 5 M E+pressions
5. %rithmetic &"erations
This section summari@es the (asic arithmetic operations.
-.2.1 2ssignment
,ssignment is term for setting a varia(le eAual to some value. ,ssignment is performed with a eAual
3>4 sign. The general form is$
variable = expression
The e+pression ma' (e a literal, varia(le, an arithmetic formula, or com(ination of each. =nl' one
assignment to a single varia(le can (e made per line.
0or e+ample, to declare the varia(le ans"er1 as a real value,
real :: answer1
and set it eAual to 2.B1C2C1C3,
answer1 = 2.71828183
The value for ans"er1 can (e changed as often as needed. However, it can onl' hold one value at a
time.
-.2.2 2''ition
The 0ortran addition operation is specified with a plus sign 3O4. 0or e+ample, to declare the varia(les,
sum, number1, number2, and number&,
integer :: sum, number1=4, number2=5, number3=3
and calculate the sum,
sum = number1 + number2
which will set the varia(le sum to 1 in this e+ample. The data t'pes of the varia(les, integer in this
e+ample, should (e the same. Iultiple varia(les can (e added on one line. The line can also include
literal values. 0or e+ample,
sum = number1 + number2 + number3 + 2
which will set the varia(le sum varia(le to 1<. ,dditionall', it will over6write the previous value of 1.
-.2.3 ubtraction
The 0ortran su(traction operation is specified with a minus sign 364. 0or e+ample, to declare the
varia(les, ans, 'alue1, 'alue2, and 'alue&,
real :: ans, value1=4.5, value2=2.5, value3=1.0
and calculate the difference,
ans = value1 value2
which will set the varia(le ans varia(le to 2.0. The data t'pes of the varia(les, real in this e+ample,
11
:hapter 5 K E+pressions
should (e the same. Iultiple varia(les can (e su(tracted on one line. The line can also include literal
values. 0or e+ample,
ans = value1 - value2 value3
which will set the varia(le ans varia(le to 1.0. ,dditionall', it will over6write the previous value of 2.0.
-.2.4 3ultiplication
The 0ortran multiplication operation is specified with an asteris) 3Y4. 0or e+ample, to declare the
varia(les, ans, 'alue1, 'alue2, and 'alue&,
real :: ans, value1=4.5, value2=2.0, value3=1.5
and calculate the product,
ans = value1 * value2
which will set the varia(le ans to 1.0. The data t'pes of the varia(les, real in this e+ample, should (e
the same. Iultiple varia(les can (e multiplied on one line. The line can also include literal values.
0or e+ample,
ans = value1 * value2 * 2.0 * value3
which will set the varia(le sum to 2B.0. ,dditionall', it will over6write the previous value of 1.0.
-.2.- Di4ision
The 0ortran division operation is specified with a slash s'm(ol 354. 0or e+ample, to declare the
varia(les, ans, 'alue1, 'alue2, and 'alue&,
real :: ans, value1=10.0, value2=2.5, value3=2.0
and calculate the Auotient,
ans = value1 / value2
which will set the varia(le ans to <.0. The data t'pes of the varia(les, real in this e+ample, should (e
the same. Iultiple varia(les can (e divided on one line. 0or e+ample,
ans = value1 / value2 / value3
which will set the varia(le sum to 2.0. ,dditionall', it will over6write the previous value of <.0.
-.2.& "#ponentiation
E+ponentiation means -raise to the power of2. 0or e+ample, 2 to the power of 3, or 2
3
is 32 Y 2 Y 24
which is C. The 0ortran e+ponentiation operation is specified with a dou(le asteris)s 3==4.
0or e+ample, to declare the varia(les, ans and 'alue1,
real :: ans, value1=2.0
20
:hapter 5 M E+pressions
and calculate the e+ponentiation,
ans = value1 ** 3
which will set the varia(le ans to C.0. The data t'pes of the varia(les, real in this e+ample, should (e
the same.
5.! Precedence of &"erations
0ortran follows the standard mathematical precedence of operations. That is multiplication and
division are performed (efore addition and su(traction. 0urther, in accordance with mathematical
standards, the e+ponentiation operation is performed (efore multiplication and division.
The following ta(le provides a partial summar' of the (asic 0ortran 15 precedence levels$
)recedence
+eve&
Operator Operation
1
st
4 unar' 6
2
nd
== e+ponentiation
3
rd
= - multiplication and division
<
th
< 4 addition and su(traction
0or operations of the same precedence level, the e+pression is evaluated left to right. /arentheses ma'
(e used to change the order of evaluation as necessar'. 0or e+ample, to declare the varia(les ans1,
ans2, num1, num2, and num&.
integer :: ans1, ans2, num1=20, num2=50, num3=10
and calculate the ans1 and ans2,
ans1 = num1 + num2 * num3
ans2 = (num1 + num2) * num3
which will set to ans1 to 520 and ans2 to B00 3(oth integers4.
5.$ Intrinsic Functions
.ntrinsic functions are standard (uilt6in functions that are provided (' 0ortran. These include a rich set
of standard functions, including the t'pical mathematical standard functions. .ntrinsic functions can (e
used in e+pressions as needed. Iost intrinsic functions accept one or more arguments as input and
return a single value.
-.4.1 3athematical ,ntrinsic %unctions
The (uilt6in functions include the standard mathematical functions such as sine, cosine, tangent, and
sAuare root.
21
:hapter 5 K E+pressions
0or e+ample, the cosine of ; is 61. .n 0ortran, to declare the varia(les x and pi,
real :: z
real, parameter :: pi = 3.14159
and then calculate the cosine of the varia(le pi,
z = cos(pi)
which will set z to 61.0. The varia(le pi is the input argument and the result returned is assigned to the
varia(le z.
-.4.2 Con4ersion %unctions
=ther intrinsic functions include functions to change the t'pe of varia(les or values. The (asic
conversion functions are as follows$
Function %'p&anation
real3Zinteger argument[4 :onvert the Zinteger argument[ to a real
value
int3Zreal argument[4 :onvert the Zreal argument[ to an integer,
truncates the fractional portion
nint3Zreal argument[4 :onvert the Zreal argument[ to an integer,
rounds the fractional portion
0or e+ample, given the following varia(le declarations,
integer :: inum1=10, inum2, inum3
real :: rnum1, rnum2 = 4.8
and calculate the ans1 and ans2,
rnum1 = real(inum1)
inum2 = int(rnum2)
inum3 = int(rnum3)
which will set to rnum1 to 10.0, inum2 to <, and inum& to 5.
-.4.3 ummary
, summar' of some of the more common intrinsic functions include$
Function De$cription
:=%384 *eturns real cosine of real argument 8 in radians.
.!T3,4 :onverts real argument , to integer, truncating 3real part4
towards @ero.
I=;3*1,*24 *eturns remainder after division of *1 on division (' *2.
*esult, *1 and *2 should (e all integer or all real t'pes.
22
:hapter 5 M E+pressions
!.!T3J4 *eturns the nearest integer to real value J 3thus rounding
up or down as appropriate4.
*E,93,4 :onverts integer argument , to real.
%.!384 *eturns real sine of real argument 8 in radians.
%?*T384 *eturns the real sAuare root of real argument 8P 8 must (e
positive.
T,!3J4 *eturns the real tangent of real argument J in radians.
, more complete list of intrinsic functions in located in ,ppendi+ >.
5.5 4ixed 4ode
.n general, mathematical operations should (e performed on varia(les of the same t'pe. 8hen (oth
integer and real values or varia(les are used in the same statement, it is called mi+ed mode.
*eal and integer operations$
1/2 = 0
1.0 + 1/4 = 1.0
1.0 + 1.0/4 = 1.25
when mi+6mode is encountered, integer is converted to real onl' when mi+ed6mode is encountered on
the same operation t'pe. :onversion ma' also occur on assignment.
"ne+pected conversions can cause pro(lems when calculating values. .n order to avoid such pro(lems,
it is strongl' recommended to not use mi+6mode. There are a series of rules associated with mi+ed6
mode operations. 0or simplicit', those rules are not covered in here.
.f it is necessar' to perform calculations with different data t'pes, li)e integers and reals, the
conversion functions should (e used correct and predicta(le results.
5.0 ,xam"les
>elow is an e+ample program that calculates velocit' (ased on acceleration and time. The program
declares the appropriate varia(les and calculate the velocit'.
program velocity
! Program to calculate the velocity from the
! acceleration and time
! Declare variables
implicit none
real :: velocity, acceleration = 128.0
real :: time = 8.0
! Display initial header
write (*,*) "Velocity Calculation Program"
write (*,*)
23
:hapter 5 K E+pressions
! Calculate the velocity
velocity = acceleration * time
write (*,*) "Velocity = ", velocity
end program velocity
,dditional information regarding how to perform input and output in the ne+t chapter. The comments
are not reAuired, (ut help ma)e the program easier to read and understand.
5.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestion (ased on this chapter.
-.5.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat is assignment operatorN
24 8hat is the e+ponentiation operatorN
34 How can an integer varia(le (e converted to a real valueN
<4 How can an real varia(le (e converted to a integer valueN
54 8hat are the two logical constantsN
E4 9ist three intrinsic functions.
B4 8rite the single 0ortran statement for each of the following formulas$
x1 =
(

(
)
(3a
2
+3b
2
+c
2
) c
x2 =
2a
c
co$(b) $in( b)
x3 =
b

( b
2
4 ac)
2 a
2<
:hapter 5 M E+pressions
-.5.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the velocit' program, compile, and e+ecute the program. :hange the declared values,
compile, and e+ecute the modified program. Verif' the results of (oth e+ecutions with a
calculator.
24 8rite a program to calculate and displa' the difference (etween time as read from a sundial and
a cloc). The difference can (e calculated with the -eAuation of time2 which is$
b = 2 ( n *1) / 3(4
e = .*7 $in(20) 7.!3 co$(b) 1.! $in(b)
8here, n is the da' num(er. 0or e+ample, n U 1 for Januar' 1, n U 2 for Januar' 2, and so on.
The program should read the value for n 3163E<4 from the user and an integer. The program
should perform the appropriate t'pe conversions, perform the reAuired calculations, and displa'
the n, b, and final e values. Test the program on a series of different values.
25
:hapter 5 K E+pressions
2E
0 'im"le In"ut and &ut"ut
%imple, unstructured, input and output can (e performed with the "rite and read statements as
e+plained in the following sections. .n a later chapter, a more structured approach will (e presented in
later sections.
0.1 &ut"ut 1 Write
,s noted from the first program, simple output can (e performed (' using the a "rite statement. 0or
e+ample$
write (*,*) "Hello World"
8hich will send the message, referred to as a string, ?e&&o 2or&d to the screen. The first -Y2 means
the default output device, which is the screen or monitor. The second -Y2 refers to the 7free format7.
Thus, the -(*,*)2 means to send it to the screen in 7free format7.
The free format allows the 0ortran compiler to determine the appropriate format for the information
(eing displa'ed. This is eas', especiall' when first getting started, (ut does not allow the program
much control over how the output will (e formatted or displa'ed on the screen.
,dditionall', the value held (' declared varia(les can (e displa'ed. 0or e+ample, to declare the
varia(les num1, num2, and num&.
integer :: num1=20, num2=50, num3=10
the write statement to displa' num1 would (e,
write (*,*) num1
The free format allows the 0ortran compiler to determine the appropriate output format for the
information (eing displa'ed.
, write statement with no string or varia(les,
write (*,*) num1
8ill displa' a (lan) line.
Iultiple varia(les and strings can (e displa'ed with one write statement. 0or e+ample, using the
previous declarations,
write (*,*) "Number 1 = ", num1, "Number 2 = ", num2
The information inside the Auotes is displa'ed as is, including capitali@ation and an' spelling errors.
8hen the Auotes are not used, it is interpreted as a varia(le. .f the varia(le is not declared, a compiler
error will (e generated. The value assigned to each varia(le will (e displa'ed. , value must have (e
assigned to the varia(le prior to attempting to displa'.
2B
:hapter E K %imple .nput and =utput
&.1.1 !utput $ Print
.n addition to the write statement, a print statement can (e used. The print statement will send output
onl' to the screen. Thus it is a more restrictive form of the write statement.
,s with the write statement, multiple varia(les and strings can (e displa'ed with one print statement.
0or e+ample, using the previous declarations,
print *,"Number 1 = ", num1, "Number 2 = ", num2
The information inside the Auotes is displa'ed as is, including capitali@ation and an' spelling errors.
8hen the Auotes are not used, it is interpreted as a varia(le. .f the varia(le is not declared, an error will
(e generated. .f the varia(le is defined, the value assigned to that varia(le will (e displa'ed.
.n general, all e+amples will use the write statement.
0. In"ut 1 +ead
To o(tain information from the user, a read statement is used. 0or e+ample, to declare the varia(les
num1, num2,
integer :: ans1, ans2
then read a value for ans1 from the user,
read (*,*) ans1
8hich will read a num(er from the user entered on the )e'(oard into the varia(le ans1. The 3Y,Y4
means to send it to read the information in 7free format7. The free format allows the 0ortran compiler to
determine the appropriate format for the information (eing read.
Iultiple varia(les can (e read with one write statement. 0or e+ample, using the previous declarations,
read (*,*) ans1, ans2
will read two values from the user into the varia(les ans1 and ans2.
%ince the read is using free format, two num(ers will (e reAuired. The num(ers can (e entered on the
same line with one more more spaces (etween them or on separate lines. The read will wait until two
num(ers are entered.
8hen reading information from the user, it is usuall' necessar' to provide a prompt in order to ensure
that the user understands that input is (eing reAuested (' the program. , suita(le write statement with
an appropriate string, followed (' a read statement will ensure that the user is notified that input is
(eing reAuested.
0or e+ample, to read a date, a program might reAuest month, date, and 'ear as three separate varia(les.
iven the following declarations,
integer :: month, date, year
the program might prompt for and read the data in the following manner,
write (*,*) "Enter date (month, date, and year)"
read (*,*) month, date, year
2C
:hapter E M %imple .nput and =utput
%ince the program is reAuesting three integers, three integers must (e entered (efore the program
continues. The three num(ers ma' (e entered on one line with a single space (etween them, with
multiple spaces or ta( (etween them, or even on three different lines as in the following e+amples$
Enter date (month, date, and year)
10 17 2009
Enter date (month, date, and year)
10
17
2009
Enter date (month, date, and year)
10 17 2009
The t'pe of num(er reAuested here is an integer, so integers should (e entered. /roviding a real
num(er or character 3i.e., letter4 would generate an error. 9ater chapters will address how to deal with
such errors.
0.! ,xam"le
>elow is an e+ample program that calculates the area of a circle. The program will declare the
appropriate varia(les, read the radius, calculate the circle area, and displa' the result.
Program circle
! Program to calculate the area of a circle
! Declare variables
implicit none
real :: radius, area
real, parameter :: pi = 3.14159
! Display initial header and blank line
write (*,*) "Circle Area Calculation Program"
write (*,*)
! Prompt for and read the radius
write (*,*) "Enter Circle Radius"
read (*,*) radius
! Calculate the circle area
area = pi * radius**2
! Display result
write (*,*) "Circle Area: ", area
end program circle
The comments are not reAuired, (ut help ma)e the program easier to read and understand. .f the
program does not wor) at first, the comments can aid in determining the pro(lem.
21
:hapter E K %imple .nput and =utput
0.$ ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
&.4.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat does the (*,*) meanN
24 8hat is the statement to output a message -/rogramming is 0un\2
34 8hat are the statements to declare and read the value for a persons age in 'ears.
&.4.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the circle area program, compile and e+ecute the program. Test the program on several
sets of input.
24 Iodif' the circle area program to reAuest a circle diameter. The formula for circler area must
(e adFusted accordingl'. *ecall that radius U diameter divided (' two. Test the program on
several sets of input.
34 T'pe in the velocit' program from the previous chapter and update to prompt for and reAuest
input for the acceleration and time, and then displa' the results. Test the program on several
sets of input.
<4 8rite a 0ortran program to read the length of the a and b sides of a right triangle and compute
the perimeter length. The program should prompt for input and displa' the values for sides a, b,
c, and the perimeter with appropriate headings.
*ecall that$
c = a
2
+b
2
perimeter = a+b+c
Test the program on several sets of input.
30
a
(
c
:hapter E M %imple .nput and =utput
54 8rite a 0ortran program compute geometric information for a Gite. The program should read
the a, c and p lengths and compute the q length. The program should
displa' an appropriate prompt, read the values, compute the answer, and
displa' the original input and the final result.
*ecall that$
q = (a
2

p
2
4
) ( c
2

p
2
4
)
Test the program on several sets of input.
31
a
p
A
c
:hapter E K %imple .nput and =utput
32
5 Program #e)elo"ment
8riting or developing programs is easier when following a clear methodolog'. The main steps in the
methodolog' are$
"nderstand the /ro(lem
:reate the ,lgorithm
;evelop the /rogram
Test5;e(ug the /rogram
To help demonstrate this process in detail, these steps will (e applied to a simple pro(lem to calculate
and displa' the period of a pendulum.
,s additional e+amples are presented in later chapters, the' will (e e+plained and presented using this
methodolog'.
5.1 6nderstand the Problem
>efore attempting to create a solution, it is important to understand the pro(lem. Ensuring a complete
understanding of the pro(lem can help reduce errors. The first step is to understand the what is
reAuired and the applica(le input information. .n this e+ample, the formula for the period of a
pendulum is$
Period = 2
L
g
1 +
1
4
$in
2
(

2
)
8here$
g U 1C0 cm5sec
2
U 3.1<151
L U /endulum length 3cm4
U ,ngle of displacement 3degree4
>oth g 3gravit'4 and should (e declared as a constants. The formula is a simplified version of the
more general case. ,s such, for ver' large, ver' small, or @ero angle values the formula will not
provide accurate results. 0or this e+ample, that is accepta(le.
,s shown, the pendulum is attached to a fi+ed point, and set into motion (' displacing the pendulum
(' an angle, , as shown in the diagram. The program must define the constants for g and , declare
the varia(les, displa' appropriate prompts, read the values for L and then calculate and displa' the
original input and the period of the pendulum with the given length and angle of displacement.
33
9
]
:hapter B K /rogram ;evelopment
5. Create the %lgorithm
The algorithm is the name for the ordered seAuence of steps involved in solving the pro(lem. =nce the
program is understood, a series of steps can (e developed to solve that pro(lem. There can (e multiple
correct solutions to a given pro(lem.
The process for creating an algorithm can (e different for different people. .n general, some time
should (e devoted to thin)ing a(out a possi(le solution. This ma' involve wor)ing on some possi(le
solution on a scratch piece of paper. =nce a possi(le solution is selected, that solution can (e
developed into an algorithm. The algorithm can (e written down, reviewed, and refined. This
algorithm is the outline of the program.
0or this pro(lem, the varia(les and constants must (e declared, the applica(le headers and prompts
displa'ed, and the values for L and read from the user. Then the period can (e calculated (ased on
the provided formula and the results displa'ed. 0ormali@ing this, the following steps can (e developed
and written down as follows$
! declare variables
! real constants -> gravity, pi
! reals -> angle, length
! display initial header
! prompt for and read the length and angle values
! calculate the period
! display the results
8hile this is a fairl' straightforward algorithm, more comple+ pro(lems would reAuire more e+tensive
algorithms. E+amples in later chapters will include more comple+ programs. 0or convenience, the
steps are written a program comments. This will allow the addition of the code to the (asic algorithm.
5.! #e)elo" the Program
>ased on the algorithm, the following program can (e created.
program period
! Program to calculate the period of a pendulum
! declare variables
! real constants -> gravity, pi
! reals -> angle, length
implicit none
real :: angle, length, pperiod
real, parameter :: gravity=980.0, pi=3.14159
! display initial header
write (*,*) "Pendulum Period Calculation Program"
write (*,*)
! prompt for and read the length and angle values
write (*,*) "Enter Length and Angle values:"
read (*,*) length, angle
3<
:hapter B M /rogram ;evelopment
! calculate the period
pperiod = 2.0 * pi * sqrt(length/gravity) * &
( 1.0 + 1.0/4.0 * sin(angle/2.0)**2 )
! display the results
write(*,*) "The period is:", pperiod
end program period
The indentation is not reAuired, (ut helps ma)e the program easier to read. !ote that the -22, -12, and
-<2 in the algorithm are entered as 2.0, 1.0, and <.0 to ensure consistent data t'ping 3i.e., all reals4. .f
the 1 over < is entered as -15<2 instead of -1.05<.02, it (e incorrect since -15<2 would provide a result of
0 3since this would (e integer division4.
5.$ Test7#ebug the Program
=nce the program is written, testing should (e performed to ensure that the program wor)s. The
testing will (e (ased on the specific parameters of the program. .n this e+ample, each of the three
possi(le values for the discriminant should (e tested.
C:\mydir> period
Pendulum Period Calculation Program
Enter Length and Angle values:
120.0 15.0
The Period is: 2.682276
K:\mydir>
,s (efore, input t'ped (' the user is shown in (old. 0or this program, the results can (e verified with a
calculator. , series of different values should (e used for testing. .f the program does not wor), the
program comments provide a chec)list of steps and can (e used to help de(ug the program.
5.4.1 "rror 0erminology
.n case the program does not wor), it helps to understand some (asic terminolog' a(out where or what
the error might (e.
5.4.1.1 Compiler "rror
:ompiler errors are generated when the program is compiled. This means that the compiler does not
understand the instructions. The compiler will provide a list of errors and the line num(er the of each
error. .t is recommended to address the errors from the top down. *esolving an error at the top can
clear multiple errors further down.
T'pical compiler errors include misspelling a statement and5or omitting a varia(le declaration. 0or
e+ample, if the correct 0ortran statement -write 3Y,Y42 is entered incorrectl' as -wrote 3Y,Y42, an error
will (e generated.
35
:hapter B K /rogram ;evelopment
.n this case, the compiler error displa'ed will appear as follows$
c:\mydir> gfortran -o period period.f95
period.f95:13.1:
wrote (*,*)
1
Error: Unclassifiable statement at (1)
The first digit, 13 in this e+ample, represents the line num(er where the error occurred. "sing a te+t
editor that displa's line num(ers, the statement that caused the error can (e Auic)l' found and
corrected.
.f the declaration for the varia(le length is omitted, the error would appear as follows$
c:\mydir> gfortran -o period period.f95
period.f95:17.18:
read (*,*) length, angle
1
Error: Symbol 'length' at (1) has no IMPLICIT type
.n this case, the error is shown on line 1C 3first digit after the -$24. However, the actual error is that the
varia(le length is not declared. Each error should (e reviewed and evaluated.
5.4.1.2 Run1time "rror
, run6time error is something that causes the program to crash. 0or e+ample, if the a num(er is
reAuested from the user and a letter is entered, that can cause occur.
0or e+ample, the period program e+pects two real num(ers to (e entered. .f the user enters letters, +
and ', in this e+ample, an error will (e generated during the e+ecution of the program as follows$
c:\mydir> period
Pendulum Period Calculation Program
Enter Length and Angle values:
x y
At line 17 of file period.f95 (unit = 5, file = 'stdin')
Fortran runtime error: Bad real number in item 1 of list input
The program was e+pecting numeric values and letters were provided. %ince letters are not meaningful
in this conte+t, it is an error and the program -crashes2 or stops with an error message.
9ater chapters will provide additional information on how to deal with such errors. "ntil then, proving
the correct data t'pe will avoid this )ind of error.
3E
:hapter B M /rogram ;evelopment
5.4.1.3 .ogic "rror
, logic error is when the program e+ecutes, (ut does not produce the correct result. 0or e+ample,
coding a provided formula incorrectl' or attempting to computer the average of a series of num(ers
(efore calculating the sum.
0or e+ample, the correct formula for the period of a pendulum is as follows$
pperiod = 2.0 * pi * sqrt(length/gravity) * &
( 1.0 + 1.0/4.0 * sin(angle/2.0)**2 )
.f the formula is t'ped incorrectl' or incompletel' as follows$
pperiod = 2.0 * pi * sqrt(length/gravity) * &
( 1.0 + 1/4 * sin(angle/2.0)**2 )
The 1 over < is entered as -15<2 which are interpreted as integers. ,s integers, -15<2 results in 0. The
compiler will accept this, perform the calculations, and provide an incorrect result.
The program would compile and e+ecute as follows.
c:\mydir> period
Pendulum Period Calculation Program
Enter Length and Angle values:
120.0 15.0
The period is: 2.198655
However, an incorrect answer would (e generated as shown. This is wh' testing the program is
reAuired. 9ogic errors can (e the most difficult to find.
=ne of the (est wa's to handle logic errors is to avoid them (' careful developing the algorithm and
writing the code.
.f the program has a logic error, one wa' to find the error is to displa' intermediate values. 0urther
information will (e provided in later chapters regarding advice on finding logic errors.
5.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
5.-.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat are the four program development stepsN
24 8hat are the three t'pes of errorsN
34 .f a program to compute the area of a rectangle uses a formula, height ^ height ^ width, what
t'pe of error would this (eN
<4 /rovide an e+ample of that would generate a compiler error.
3B
:hapter B K /rogram ;evelopment
5.-.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the pendulum period calculation program, compile, and e+ecute the program. Test the
program using several different input values.
24 :reate a program to prompt for and read the circle area from the user and calculate the
circumference of a circle using the following formula$
circumference = 2 Circlerea
Test the program using several different input values.
34 :reate a program to prompt for and read the radius of a sphere from the user and calculate the
surface area of the sphere using the following formula$
sphere !urface rea = 4 r
2
Test the program using several different input values.
<4 :reate a program to prompt for and read the radius of a sphere from the user and calculate the
sphere volume using the following formula$
sphere"olume = ( 4 / 3)r
3
Test the program using several different input values.
3C
8 'election 'tatements
8hen writing a program, it ma' (e necessar' to ta)e some action (ased on the outcome of comparing
the values of some varia(les. ,ll programming languages have some facilit' for decision6ma)ing.
That is, doing one thing if some condition is true and 3optionall'4 doing something else if it is not.
0ortran .0 statements and5or :,%E statements are used to allow a program ma)es decisions.
8.1 +elational ,x"ressions
The first step is to compare two values, often contained in varia(les. The wa' two values are compared
is with relational operators. The varia(les are often referred to as operands. *elational operators are
used (etween varia(les or operands of similar t'pes. That is real to real, integer to integer, logical to
logical, and character5string to character5string.
The (asic relational operators are$
6e&ationa&
Operation
6e&ationa& Operator
@norma&A
6e&ationa& Operator
@a&ternateA
reater than B .gt.
reater than or
eAual
B> .ge.
9ess than C .&t.
9ess than or eAual C> .&e.
EAual to >> .eD.
!ot eAual to -> .ne.
The normal form will (e used for e+amples in this te+t. However, the alternate form ma' (e used at
an' time. The alternate forms are used to support older 0ortran programs.
, relational operation is used to form a relational e+pression. The result of a relational e+pression must
alwa's result in either a true or (alse result.
The ->>2 3two eAual signs4 is used to compare. The ->2 3single eAual4 is used for assignment 3setting
a varia(le4. The ->>2 does not change an' values, while the ->2 does.
0or e+ample, given the declaration of,
integer :: gamelives
it might (e useful to )now if the current value of gamelives is greater than 0.
31
:hapter C K %election %tatements
.n this case, the relational e+pression would (e,
(gamelives == 0)
8hich will result in a true or (alse result (ased on the value of -gamelives2.
8. Logical &"erators
9ogical operators are used (etween two logical varia(les or two logical e+pressions. The' are$
+ogica& Operator %'p&anation
.and. the result is true if both operands are true
.or. the result is true if either operand is true
.not. logical negate 3if true, ma)es false and if
false, ma)es true4
9ogical operators are used to com(ine relational operations as needed.
0or e+ample, given the declaration of,
integer :: gamelives, extralives
it might (e useful to )now if the current value of gamelives is greater than 0. .n this case, the
relational operation would (e,
( (gamelives == 0) .and. (extralives == 0) )
which will result in a true or (alse result. %ince the ,!; logical operation is used, the final result will
(e true onl' if (oth logical e+pressions are true.
,nother wa' of chec) the status might (e,
( (gamelives > 0) .or. (extralives > 0) )
which still results in a true or (alse result. However, since the or logical operation is used, the final
result will (e true if either logical e+pressions is true.
The relational operators have higher precedence than logical operators.
8.! IF 'tatements
.0 statements are used to perform different computations or actions (ased on the result of a logical
e+pression 3which evaluates to true or false4. There are a series of different forms of the (asic .0
statement. Each of the forms is e+plained in the following sections.
<0
:hapter C M %election %tatements
6.3.1 ,% 0/"N tatement
The .0 statement, using the relational operators, is how programs ma)e decisions. The general format
for an .0 statement is as follows$
if ( <relational expression> ) then
<fortran statement(s)>
end if
8here the Zfortran statements[ ma' include one or more valid 0ortran statements.
0or e+ample, given the declaration of,
integer :: gamelives
(ased on the current value of gamelives is, a reasona(le .0 statement might (e$
if ( gamelives == 0 ) then
write (*,*) "Game Over."
write (*,*) "Please try again."
end if
8hich will displa' the message -ame =ver2 if the value of gamelives is less than or eAual to 0.
6.3.1.1 ,% 0/"N tatement7 imple %orm
,dditionall', another form of the .0 statement includes
if ( <relational expression> ) <fortran statement>
.n this form, a single statement is e+ecuted if the relational e+pression evaluates to true. The previous
e+ample might (e written as
if ( gamelives == 0 ) write (*,*) "Game Over."
.n this form, no -then2 or -end if2 are reAuired. However, onl' one statement can (e e+ecuted.
6.3.2 ,% 0/"N "." tatement
The .0 THE! E9%E statement e+pands the (asic .0 statement to also allow a series of statements to (e
performed if the logical e+pression evaluates to (alse.
The general format for an .0 THE! E9%E statement is as follows$
if ( <relational expression> ) then
<fortran statement(s)>
else
<fortran statement(s)>
end if
8here the Zfortran statements[ ma' include one or more valid 0ortran statements.
<1
:hapter C K %election %tatements
0or e+ample, given the declaration of,
integer :: gamelives
(ased on the current value of gamelives is, a reasona(le .0 THE! E9%E statement might (e$
if ( gamelives > 0 ) then
write (*,*) "Still Alive, Keep Going!"
else
write (*,*) "Extra Life Granted."
gameslives = 1
end if
8hich will displa' the message -%till ,live, Geep oing2 if the value of gamelives is greater than 0
and displa' the message -E+tra 9ife ranted2 if the value of gamelives is less than 0.
6.3.3 ,% 0/"N "." ,% tatement
The .0 THE! E9%E .0 statement e+pands the (asic .0 statement to also allow a series of .0 statements
to (e performed in a series.
The general format for an .0 THE! E9%E .0 statement is as follows$
if ( <relational expression> ) then
<fortran statement(s)>
else if ( <relational expression> ) then
<fortran statement(s)>
else
<fortran statement(s)>
end if
8here the Zfortran statements[ ma' include one or more valid 0ortran statements.
0or e+ample, given the declaration of,
integer :: gamelives
(ased on the current value of gamelives is, a reasona(le .0 THE! E9%E .0 statement might (e$
if ( gamelives > 0 ) then
write (*,*) "Still Alive, Keep Going!"
else if ( gamelives < 0 )
write (*,*) "Sorry, game over."
else
write (*,*) "Extra Life Granted."
gameslives = 1
end if
8hich will displa' the message -%till ,live, Geep oing2 if the value of gamelives is greater than 0,
displa' the message -%orr', game over2 if the value of game lives is Z 0, and displa' the message
-E+tra 9ife ranted2 if the value of gamelives is eAual to 0.
<2
:hapter C M %election %tatements
8.$ ,xam"le &ne
,s previousl' descri(ed, writing or developing programs is easier when following a methodolog'. ,s
the program (ecome more comple+, using a clear methodolog' is even more important. The main
steps in the methodolog' are$
"nderstand the /ro(lem
:reate the ,lgorithm
;evelop the /rogram
Test5;e(ug the /rogram
To help demonstrate this process in detail, these steps will (e applied to a familiar pro(lem as an
e+ample. The e+ample pro(lem is to calculate the solution of a Auadratic eAuation in the form$
a x
2
+ b x + c = ,
Each of the steps, as applied to this pro(lem will (e reviewed.
6.4.1 8n'erstan' the Problem
>efore creating a solution, it is important to understand the pro(lem. Ensuring a complete
understanding of the pro(lem can help reduce errors.
.t is )nown that the solution to the Auadratic eAuation is as follows$
x =
b

(b
2
4a c)
2a
.n the Auadratic eAuation, the term b
2
<a c is the discriminant of the eAuation. There are three
possi(le results for the discriminant as descri(ed (elow$
.f b
2
<ac 0 then there are two distinct real roots to the Auadratic eAuation. These two
solutions represent the two possi(le answers. .f the eAuation solution is graphed, the curve
representing the solution will cross the x6a+is 3i.e., representing xU04 in two locations.
.f b
2
<ac = 0 then there is a single, repeated root to the eAuation. .f the eAuation solution
is graphed, the curve representing the solution will cross the x6a+is in one location.
.f b
2
<ac 0 then there are two comple+ roots to the eAuation. .f the eAuation solution is
graphed, the curve representing the solution will not cross the x6a+is and this no real num(er
solution. However, mathematicall' the sAuare root of a negative value will provide a comple+
result. , comple+ num(er includes a real component and an imaginar' component.
, correct solution must address each of these possi(ilities. 0or this pro(lem, it is appropriate to use
real values.
<3
:hapter C K %election %tatements
The relationship (etween the discriminant and the t'pes of solutions 3two different solutions, one
repeated solution, or no real solutions4 is summari@ed in the (elow ta(le$
)o$itive Di$criminant Eero Di$criminant 7egative Di$criminant
Two real solutions =ne real solution Two comple+ solutions
E+ample$
3+
2
1+3
E+ample$
2+
2
<+2
E+ample$
3+
2
3+3
Two distinct x6intercepts =ne x6intercept !o x6intercept
*oot 1 U 60.3C2
*oot 2 U 62.E1C
*oot 1 U 61.0 *oot U 60.5 O 0.CEE
*oot U 60.5 6 0.CEE
The e+amples provided a(ove are included in the e+ample solution in the following sections.
6.4.2 Create the 2lgorithm
The algorithm is the name for the ordered seAuence of steps involved in solving the pro(lem. The
varia(les must (e defined and an initial header displa'ed. 0or this pro(lem, the a, b, and c values will
need to (e read from the user. 0ormali@ing this, the following steps can (e developed.
! declare variables
! reals -> a, b, c, discriminant, root1, root2
! display initial header
! read the a, b, and c values
Then, the discriminant can (e calculated.
>ased on the discriminant value, the appropriate set of calculations can (e performed.
! calculate the discriminant
! if discriminant is 0,
! calculate root
<<
9 9
9
:hapter C M %election %tatements
! if discriminant is >0,
! calculate root1 and root2
! display root1 and root2
! if discriminant is >0,
! calculate complex root1 and root2
! display complex root1 and root2
0or convenience, the steps are written a program comments.
6.4.3 De4elop the Program
>ased on the algorithm, the following program can (e created.
program quadratic
! Quadratic equation solver program
! declare variables
! reals -> a, b, c, discriminant, root1, root2
implicit none
real :: a, b, c
real :: discriminant, root1, root2
! display initial header
write (*,*) "Quadratic Equation Solver Program"
write (*,*) "Enter A, B, and C values"
! read the a, b, and c values
read (*,*) a, b, c
! calculate the discriminant
discriminant = b ** 2 4.0 * a * c
! if discriminant is 0,
! calculate root
if ( discriminant == 0 ) then
root1 = -b / (2.0 * a)
write(*,*) "This equation has one root:"
write(*,*) "root = ", root1
end if
! if discriminant is >0,
! calculate root1 and root2
! display root1 and root2
if ( discriminant > 0 ) then
root1 = (-b + sqrt(discriminant)) / (2.0 * a)
root2 = (-b - sqrt(discriminant)) / (2.0 * a)
write(*,*) "This equation has two real roots:"
write(*,*) "root 1 = ", root1
write(*,*) "root 2 = ", root2
end if
! if discriminant is >0,
! calculate complex root1 and root2
<5
:hapter C K %election %tatements
! display complex root1 and root2
if ( discriminant < 0 ) then
root1 = -b / (2.0 * a)
root2 = sqrt(abs(discriminant)) / (2.0 * a)
write(*,*) "This equation has two real roots:"
write(*,*) "root 1 = ", root1, "+i", root2
write(*,*) "root 2 = ", root1, "-i", root2
end if
end program quadratic
The indentation is not reAuired, (ut does help ma)e the program easier to read.
6.4.4 0est9Debug the Program
=nce the program is written, testing should (e performed to ensure that the program wor)s. The
testing will (e (ased on the specific parameters of the program. .n this e+ample, each of the three
possi(le values for the discriminant should (e tested.
C:\mydir> quad
Quadratic Equation Solver Program
Enter A, B, and C values
2 4 2
This equation has one root:
root = -1.0000000
C:\mydir> quad
Quadratic Equation Solver Program
Enter A, B, and C values
3 9 3
This equation has two real roots:
root 1 = -0.38196602
root 2 = -2.6180339
C:\mydir> quad
Quadratic Equation Solver Program
Enter A, B, and C values
3 3 3
This equation has two real roots:
root 1 = -0.50000000 +i 0.86602539
root 2 = -0.50000000 -i 0.86602539
C:\mydir>
,dditionall', these results can (e verified with a calculator.
8.5 ',L,CT C%', 'tatement
, %E9E:T :,%E statement, often referred to as a :,%E statement, is used to compare a given value
with preselected constants and ta)e an action according to the first constant to match. , :,%E
statement can (e hand' to select (etween a series of different possi(ilities or cases.
<E
:hapter C M %election %tatements
The select case varia(le or e+pression must (e of t'pe integer, character, or logical. , real t'pe is not
allowed. >ased on the selector, a set of one or more of 0ortran statements can (e e+ecuted.
The general format of the %E9E:T :,%E statement is$
select case (variable)
case (selector-1)
<fortran statement(s)-1>
case (selector-2)
<fortran statement(s)-2>
.
.
.
case (selector-n)
<fortran statement(s)-n>
case default
<fortran statement(s)-default>
end select
where Zfortran statement3s461[, Zfortran statement3s462[, Zfortran statement3s463[, ..., Zfortran
statement3s46n[ and Zfortran statement3s46default[ are seAuences of one or more e+ecuta(le statements.
The selector61, selector62, selector63, ..., and selector6n are called selector lists. Each :,%E selector
list ma' contain a list and5or range of integers, character or logical constants, whose values ma' not
overlap within or (etween selectors. , selector6list is either a single or list of values, separated ('
commas. Each selector list must (e one of the following forms.
( value )
( value-1 : value-2 )
( value-1 : )
( : value-2 )
where value, value61 and value62 are constants or literals. The t'pe of these constants must (e identical
to that of the selector.
The first form has onl' one value
The second form means all values in the range of value61 and value62 3inclusive4. .n this form,
value61 must (e less than value62
The third form means all values that are greater than or eAual to value61
The fourth form means all values that are less than or eAual to value62
.n order, each selector e+pression is evaluated. .f the varia(le value is the selector or in the selector
range, then the seAuence of statements in Zfortran statement3s4[ are e+ecuted.
.f the result is not in an' one of the selectors, there are two possi(ilities$
if :,%E ;E0,"9T is there, then the seAuence of statements in statements6;E0,"9T are
e+ecuted, followed (' the statement following E!; %E9E:T
if the :,%E ;E0,"9T is not there, the statement following E!; %E9E:T is e+ecuted
The constants listed in selectors must (e uniAue. The :,%E ;E0,"9T is optional. >ut with a :,%E
;E0,"9T, 'ou are guaranteed that whatever the selector value, one of the la(els will (e used. The
<B
:hapter C K %election %tatements
place for :,%E ;E0,"9T can (e an'where within a %E9E:T :,%E statementP however, putting it at
the end would (e more natural.
0or e+ample, given the declarations,
integer :: hours24, hours12
character(2) :: ampm
the following case statement,
select case (hours24)
case (0)
hours12 = 12
ampm = "am"
case (1:11)
hours12 = hours24
ampm = "am"
case (12)
hours12 = hours24
ampm = "pm"
case (1:11)
hours12 = hours24 - 12
ampm = "pm"
end select
might (e useful for to convert 2<6hour time into 126hour time.
,dditionall', the selectors can (e com(ined and separated (' commas. 0or e+ample, given the
declarations,
integer :: monthnumber, daysinmonth
character(9) :: monthname
the following case statement,
select case (monthnumber)
case (1,3,5,7,8,10,12)
daysinmonth = 31
case (2)
if (mod(year,4)==0) then
daysinmonth = 29
else
daysinmonth = 28
end if
case (2,4,6,9,11)
daysinmonth = 30
case default
write (*,*) "Error, month number not valid."
end select
might (e useful to determine the num(er of da's in a given month. The leap6'ear calculation is not
complete, (ut is adeAuate if the range of the 'ear is sufficientl' limited.
<C
:hapter C M %election %tatements
8.0 ,xam"le T*o
, t'pical pro(lem is to assign grades (ased on a t'pical grading standard.
6.&.1 8n'erstan' the Problem
0or this e+ample, the program will assign grades using the following grade scale$
, > : ; 0
,[U10 C0 6 C1 B0 6 B1 E0 6 E1 ZU51
The program will read three test scores, compute the average, and displa' the appropriate grade (ased
on the average.
6.&.2 Create the 2lgorithm
The algorithm is the name for the ordered seAuence of steps involved in solving the pro(lem.
0or this pro(lem, the varia(les will (e declared and an initial header displa'ed. Then, the test1, test2,
and test2 values will need to (e read from the user.
! declare variables
! reals -> test1, test2, test2
! integer -> testave
! display initial header
! read the test1, test2, and test2 values
!e+t, the average can (e calculated. The average will (e converted to the nearest integer and, (ased on
that, the appropriate grade can (e determined and displa'ed. 0ormali@ing this, the following steps can
(e developed.
! calculate the testave and convert to integer
! determine grade
! A - >= 90
! B - 80 to 89
! C - 70 to 79
! D - 60 to 69
! F - <= 59
0or convenience, the steps are written a program comments.
6.&.3 De4elop the Program
>ased on the algorithm, the following program can (e created.
program grades
! declare variables
implicit none
<1
:hapter C K %election %tatements
real :: test1, test2, test2
integer :: testave
! display initial header
write (*,*) "Grade Assignment Program"
write (*,*)
write (*,*) "Enter test 1, test 2 and test 3 values"
! read the test1, test2, and test2 values
read (*,*) test1, test2, test3
! calculate the average and convert to integer
testave = nint ((test1 + test2 + test3)/3.0)
! determine grade
! A >= 90, B 80-89, C 70-79, D 60-69, F <= 59
select case (testave)
case(90:)
write (*,*) "Grade is: A"
case(80:89)
write (*,*) "Grade is: B"
case(70:79)
write (*,*) "Grade is: C"
case(60:69)
write (*,*) "Grade is: D"
case(:59)
write (*,*) "Grade is: F"
end select
end program grades
The indentation is not reAuired, (ut does help ma)e the program easier to read.
6.&.4 0est9Debug the Program
=nce the program is written, testing should (e performed to ensure that the program wor)s. The
testing will (e (ased on the specific parameters of the program.
.n this e+ample, each of the three possi(le values for the discriminant should (e tested.
C:\mydir> grade
Grade Assignment Program
Enter test 1, test 2 and test 3 values
70 80 90
Grade is: B
C:\mydir>
The program should (e tested with a series of data items to ensure appropriate grade assignment for
each grade. Test values for each grade should (e entered for the testing.
50
:hapter C M %election %tatements
8.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
6.5.1 Quiz Questions
>elow are some Aui@ Auestions.
14 9ist the si+ relational operatorsN
24 9ist the three (asic logical operatorsN
34 0or each of the following, answer .true. or .:a&$e. in the space provided.
boolean :: b1 = .true., b2=.false., b3=.true.
integer :: i=5, j=10
( b1 .or. b2 ) ______________
( b1 .or. b3 ) ______________
( b1 .and. b2 ) ______________
( b1 .and. b3 ) ______________
( (b1 .or. b2) .and. b3 ) ______________
( b1 .or. (b2 .and. b3) ) ______________
( .not. ( i < j ) ) ______________
( j < i ) ______________
<4 8rite the 0ortran .0 THE! statement to displa' the message Lame =verL if the integer
varia(le lives is _ to 0.
54 8rite the 0ortran .0 THE! statement to chec) the integer varia(le num and if the value is Z
0, ta)e the a(solute value of the num(er and displa' the message, Lnum was made positiveL.
E4 8rite the 0ortran statements to compute the formula
z=
x
y
assuming the values for integer
varia(les x, #, and z are previousl' set. However, if #U0, do not compute the formula, set zU0,
and displa' an error message, LW not calculatedL.
B4 8rite the single .0 THE! E9%E .0 statement reAuire to compute the following formula using
real varia(les f, x, and #. #ou ma' assume the values for x and # have (een previousl' set.
f ( x)=
x
2
# if x,.,
x # if x>,.,
51
:hapter C K %election %tatements
6.5.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the Auadratic eAuation program, compile, and e+ecute the program. /rovided input
values that will chec) each of the possi(le outputs.
24 8rite a 0ortran program to prompt for and read the 'ear that a person was (orn. The 'ear must
(e (etween 1100 and 2001. .f an invalid entr' is read, the program should displa' the message,
L%orr', that is not a valid 'ear.L and re6prompt. .f the correct value is not provided after 3
attempts, the program should displa' the message L%orr', please 'our having pro(lems.L and
terminate. =nce a valid 'ear is read, the should displa' the 'ear and a message Lis a leap 'earL
or Lis not a leap 'earL. .nclude program statements, appropriate declarations, prompts, read
statements, calculations, and write statements. Test the program on a series of input values.
34 T'pe in the grades program, compile, and e+ecute the program. Test the program on a series of
input values that will chec) each grade.
<4 Iodif' the grades program to handle the following grade assignmentP
, ,6 >O > >6 :O : :6 ; 0
[1< 13610 C16CB CE6C< C36C0 B16BB BE6B< B36B0 E16E0 Z51
:ompile, and e+ecute the program. Test the program on a series of input values that will chec)
each grade.
54 8rite a 0ortran program to prompt and read (ahrenheit as an integer, convert to celsius, and
displa' the result as a real. The formula to convert (ahrenheit to celsius is
celsius =

5
1

(ahrenheit32
The (ahrenheit value must (e (etween 650.0 and 150.0 3inclusive4. .f the (ahrenheit value is
out of range, the program should displa' an error message, LTemperature out of rangeL, and re6
prompt. .f there are 3 invalid temperatures, the program should displa' L%orr' 'our having
pro(lems.L and terminate. The calculations must (e performed as real. .nclude program
statements, appropriate declarations, prompts, read statements, calculations, and write
statements. Test the program on a series of input values.
E4 8rite a 0ortran to program that reads an item cost 3real num(ers4 and amount tendered 3real
num(er4 and compute the correct change. The correct change should (e returned as the num(er
of twenties, tens, fives, ones, Auarters, dimes, nic)els, and pennies. The main program should
ensure that the amount paid e+ceeds the item cost and, if not, displa' an appropriate error
message. Test the program on a series of input values.
52
:hapter C M %election %tatements
B4 8rite a 0ortran to program that reads a num(er from the user that represents a television
channel and then uses a :,%E construct to determine the call letters for that station.
Channe& Ca&& +etter$ .::i&iation
3 GV>: !>:
5 GVV" 0=J
C G9,% :>%
10 G9VJ /u(lic
13 GT!V ,>:
The program should displa' an appropriate message if an invalid or unassigned channel is
entered. Test the program on a series of input values that will show each station.
53
:hapter C K %election %tatements
5<
9 Loo"ing
8hen a series of 0ortran statements need to (e repeated, it is referred to as a loop or do$loop. ,
0ortran do$loop is a special control statement that allows a 0ortran statement or set of statements to (e
e+ecuted multiple times. This repetition can (e (ased on a set num(er of times, referred to as counter
controlled, or (ased on a logical condition, referred to as conditionall' controlled. Each of these
looping methods is e+plained in the following sections.
9.1 Counter Controlled Loo"ing
, counter controlled loop is repeats a series of one or more 0ortran statements a set num(er of times.
The general format of the counting loop is$
do count_variable = start, stop, step
<fortran statement(s)>
end do
where the count varia(le must (e an integer varia(le, start, stop, and step are integer varia(les or
integer e+pressions. The step value is optional. .f it is omitted, the default value is 1. .f used, the step
value cannot (e @ero. The Zfortran statement3s4[ is a seAuence of statements and is referred to as the
bod% of the do6loop. #ou can use an' e+ecuta(le statement within a do6loop, including .06THE!6
E9%E6E!; .0 and even another do6loop. >efore the do6loop starts, the values of start, stop, and step
are computed e+actl' once. Iore precisel', during the course of e+ecuting the do6loop, these values
will not (e re6computed.
The count varia(le receives the value of start varia(le or e+pression. .f the value of control6var is less
than or eAual to the value of stop6value, the Zfortran statement3s4[ part is e+ecuted. Then, the value of
step 31 if omitted4 is added to the value of control6var. ,t the end, the loop goes (ac) to the top and
compares the values of control6var and stop6value.
.f the value of control6var is greater than the value of final6value, the do$loop completes and the
statement following end do is e+ecuted.
0or e+ample, with the declarations,
integer :: counter, init=1, final=10, sum=0
the following do6loop,
do counter = init, final
sum = sum + counter
end do
write (*,*) "Sum is: ", sum
will add the num(ers (etween 1 and 10 which will result in 55. %ince the step was not specified, it is
defaulted 1.
55
:hapter 1 K 9ooping
,nother e+ample, with the declarations,
integer :: counter, init=1, final=10, step=2
and the following do6loop,
do counter = init, final, step
write (*,*) counter
end do
will displa' the odd num(ers (etween 1 and 10 31, 3, 5, B, 14.
,nother e+ample would (e to read some num(ers from the user and compute the sum and average of
those num(ers. The e+ample as)s the user how man' num(ers, reads that man' num(ers, computes
the sum, and the computes the average, and displa's the results.
program average
implicit none
integer :: count, number, sum, input
real :: average
write(*,*) "Enter count of numbers to read"
read(*,*) count
sum = 0
do number = 1, count
read(*,*) input
sum = sum + input
end do
average = real(sum) / real(count)
write *(*,*) "Average = ", average
end program average
The use of the function real)* converts the sum and count varia(les from integers to real values as
reAuired for the average calculation. 8ithout this conversion, sum5count division would (e interpreted
as dividing an integer (' an integer, 'ielding an integer result.
, final e+ample of a counter controlled loop is to compute the factorial of a positive integer. The
factorial of an integer n, written as n\, is defined to (e the product of 1, 2, 3, ..., n61, and n. Iore
precisel', n\ U 1 Y 2 Y 3 Y ... Y n.
integer :: factorial, n, i
factorial = 1
do i = 1, n
factorial = factorial * i
end do
the a(ove do6loop iterates n times. The first iteration multiplies factorial with 1, the second iteration
multiplies factorial with 2, the third time with 3, ..., the i
th
time with i and so on. Thus, the values that
are multiplied with the initial value of factorial are 1, 2, 3, ..., n. ,t the end of the do6loop, the value of
factorial is 1 Y 2 Y 3 Y ... Y n which is nF.
5E
:hapter 1 M 9ooping
9. ,9IT and C:CL, 'tatements
The e+it and c'cle statements are used to modif' the e+ecution of a do6loop. The exit statement is used
to e+it a loop. The e+it can (e used alone, (ut it is t'picall' used with a conditional statement to allow
e+iting a loop (ased on a specific condition. The exit statement can (e used in a counter controlled
loop or a conditionall' controlled loop.
0or e+ample, given the following declarations,
integer :: i
the following loop,
do i = 1, 10
if (i == 5) exit
write(*,*) i
end do
will displa' the num(ers from 1 to < s)ipping the remaining iterations. %ince the varia(le i is chec)ed
(efore the write statement, the value is not displa'ed with i is 5 and the loop is e+ited without
completing the remaining iterations.
The c%cle statement will s)ip the remaining portion of the do6loop and start (ac) at the top. The c%cle
statement can (e used in a counter controlled loop or a conditionall' controlled loop. .f the c'cle
statement is used within a counter controlled loop, the ne+t inde+ counter is updated to the ne+t
iteration, which could terminate the loop.
9.! Counter Controlled ,xam"le
.n this e+ample we will write a 0ortran program to find the difference (etween the sum of the sAuares
and the sAuare of the sum of the first & natural num(ers.
:.3.1 8n'erstan' the Problem
.n order to find the difference (etween the sum of the sAuares and the sAuare of the sum of the first &
natural num(ers, we will need to find (oth the sum of the sAuares and the sAuare of the sum. 0or
e+ample, the sum of the sAuares of the first ten natural num(ers is,
1
2
2
2
10
2
= 3C5
The sAuare of the sum of the first ten natural num(ers is,
1 2 10
2
= 55
2
= 3025
Hence the difference (etween the sum of the sAuares of the first ten natural num(ers and the sAuare of
the sum is 3025 6 3C5 U 2E<0.
The program will displa' the & value, the sum of the sAuares, the sAuare of the sum, and the difference
for each num(er from 2 to a given & value. The program should prompt for and read the & value. The
program will displa' appropriate headers.
5B
:hapter 1 K 9ooping
:.3.2 Create the 2lgorithm
0or this pro(lem, first we will need to read the & value. Then, we will loop from 1 to the & value and
find (oth the sum of the sAuares and the sAuare of the sum.
! declare variables
! integer -> i, j, n, SumOfSqrs, SqrOfSums
! display initial header
! prompt for and read the n value
! loop from 1 to N
! compute sum of squares
! compute sums
! square the sums
! compute difference between sum of squares and square of sums
! display results
0or convenience, the steps are written a program comments.
:.3.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program difference
! declare variables
implicit none
integer :: i, n, SumOfSqrs=0, SqrOfSums=0, difference
! display initial header
write(*,*) "Example Program"
write(*,*) " Difference between sum of squares "
write(*,*) " and square of sums"
write(*,*)
! prompt for and read the n value
write(*,*) "Enter N value: "
read(*,*) n
! loop from 1 to N
do i = 1, n
! compute sum of squares
SumOfSqrs = SumOfSqrs + i**2
! compute square of sums
SqrOfSums = SqrOfSums + i
end do
! square the sums
SqrOfSums = SqrOfSums**2
! compute difference between sum of squares and square of sums
difference = SqrOfSums - SumOfSqrs
5C
:hapter 1 M 9ooping
! display results
write(*,*) "Difference: ", difference
end program difference
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
:.3.4 0est9Debug the Program
0or this pro(lem, the testing would (e to ensure that the results match the e+pected value. %ome
e+pected results can (e determined with a calculator or a spreadsheet. .f the program does not provided
the correct result, one or (oth of the intermediate results, !um'f!qrs or !qr'f!ums, ma' (e incorrect.
These values can (e displa'ed with a temporar' write statement to determine which might not (e
correct. .f the pro(lem is still not found, the intermediate values calculated during the loop can also (e
displa'ed with a write statement. The output can (e reviewed to determine what the program is doing
3and what ma' (e wrong4.
9.$ Conditional Controlled Loo"ing
, conditional controlled loop repeats a series of one or more 0ortran statements (ased on a condition.
,s such, the loop ma' e+ecute a indeterminate num(er of times.
=ne form of the conditional loop is$
do while (logical expression)
<fortran statement(s)>
end do
.n this form, the logical e+pression is re6chec)ed at the top of the loop on each iteration.
, more general format of the conditional loop is$
do
<fortran statement(s)>
end do
,s is, this loop will continue forever. /ro(a(l' not so good. , selection statement, such as an .0
statement, and an exit statement would (e used to provide an means to terminate the looping. 0or
e+ample,
do
<fortran statement(s)>
if (logical expression) exit
<fortran statement(s)>
end do
8ould stop looping onl' when the logical e+pression evaluates to true. The e+it statement can used
used in multiple times in different locations as needed. ,n .0 statement, in an' form, can (e used for
either the e+it of c'cle statements.
51
:hapter 1 K 9ooping
0or e+ample, a conditional loop could (e used to reAuest input from the user and )eep re6prompting
until the input is correct.
integer :: month
do
write (*,*) "Enter month (1-12): "
read (*,*) month
if (month >= 1 .and. month <= 12) exit
write (*,*) "Error, month must be between 1 and 12."
write (*,*) "Please re-enter."
end do
This will )eep re6prompting an unlimited num(er of times until the correct input 3a num(er (etween 1
and 124 is entered.
%ince a counter controlled ;= loop reAuires an integer loop counter, another use of conditional loops
would (e to simulate a real counter. 0or e+ample, to displa' the values from 1.5 to <.5 stepping ('
0.25, the following conditional loop could (e used.
real :: value = 1.5
do
write (*,*) "Value = ", value
value = value + 0.25
end do
The values and step can (e adFusted as needed.
9.5 Conditionally Controlled Loo" ,xam"le
.n this e+ample we will write a 0ortran program read a valid date from the user. The date will consist
of three values one for each of the month, date, and 'ear. This e+ample will use some of the previous
e+ample fragments.
:.-.1 8n'erstan' the Problem
0or this limited e+ample, we will reAuest a date where the 'ear is (etween 11B0 and 2020. The month
must (e (etween 1 and 12. The date will depend on the month since some months have 30 or 31 da's.
0e(ruar' has either 2C da's or 21 da's if it is a leap 'ear. ;ue to the limited allowa(le range of the
'ear, the determination of a leap 'ear can (e performed (' chec)ing if the 'ear is evenl' divisi(le (' <
3which implies a leap 'ear4.
:.-.2 Create the 2lgorithm
0or this pro(lem, we will need to read the three values 3month, date, and 'ear4. Then, we will chec)
the values to ensure that date is valid. Then, we will chec) the month first and then the 'ear since it
will (e used to chec) the date. The months Januar', Iarch, Ia', Jul', ,ugust, =cto(er, and ;ecem(er
have 31 da's. The months ,pril, June, %eptem(er, and !ovem(er have 30 da's. 0e(ruar' has 2C da's
E0
:hapter 1 M 9ooping
unless the 'ears is evenl' divisi(le (' <, in which case 0e(ruar' has 21 da's.
! declare variables; integer -> month, date, year
! display initial header
! loop
! request month, date, and year
! read month, date, and year
! check month (1-12)
! check year (1970-2020)
! check date
! 1,3,5,7,8,10,12 31 days
! 4,6,9,11 30 days
! 2 if modulo of year/4 is 0 29 days
! 2 if modulo of year/4 is /= 0 28 days
! display results
0or convenience, the steps are written a program comments.
:.-.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program datecheck
! declare variables
implicit none
integer :: month, date, year, datemax
! display initial header
write(*,*) "Date Verification Example"
! loop
do
! request month, date, and year
write(*,*) "Date Verification Example"
! read month, date, and year
read (*,*) month, date, year
! check month (1-12)
if ( month < 1 .or. month > 12 ) then
write(*,*) "Error, invalid month"
cycle
end if
! check year (1970-2020)
if ( year < 1970 .or. year > 2020 ) then
write(*,*) "Error, invalid year"
cycle
end if
! check date
E1
:hapter 1 K 9ooping
! 1,3,5,7,8,10,12 31 days
! 4,6,9,11 30 days
! 2 if modulo of year/4 is 0 29 days
! 2 if modulo of year/4 is /= 0 28 days
select case (month)
case (1,3,5,7,8,10,12)
datemax = 31
case (2)
if (mod(year,4)==0) then
datemax = 29
else
datemax = 28
end if
case (4,6,9,11)
datemax = 30
end select
if ( date < 1 .or. date > datemax ) then
write (*,*) "Error, invalid date."
cycle
end if
exit
end do
! display results
write(*,*) "Valid Date is:", month, date, year
end program datecheck
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
:.-.4 0est9Debug the Program
0or this pro(lem, the testing would (e to ensure that the results match the e+pected value. This will
reAuire entering a series of different dates and verif'ing that the displa'ed output is correct for the
given input data.
9.0 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
:.&.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat happen when an exit statement is e+ecutedN
24 How man' exit statements can (e included in a loopN
34 8hat happen when an continue statement is e+ecutedN
E2
:hapter 1 M 9ooping
<4 How man' continue statements can (e included in a loopN
54 .f there are multiple c%cle statements in a loop, which one will (e e+ecutedN
E4 8hat is the output of the following 0ortran statements. ,ssume sum and i are declared as
integers.
sum = 0
do i = 1, 5
sum = sum + i
end do
write(*,*) "The SUM is:", sum
B4 8hat is the output of the following 0ortran statements. ,ssume i and ( are declared as integer.
do i = 1, 3
do j = 1, 2
write(*,*) i, " * ", j, " = ", (i*j)
end do
end do
write(*,*) "end 2"
C4 ,re the following 0ortran statements valid or invalidN .f valid, what will happenN
do i = 3, 2
write(*,*) i
end do
do i = 3, 3
if ( i == 3 ) then
write(*,*) i
end do
end if
14 8hat is the limit of statements that can (e included in a loopN
104 8hen an .0 statements 3an' form4 is nested inside a loop, what must (e done to ensure the
statements are validN
:.&.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the difference program, compile, and e+ecute the program. Test the program on a series
of different input values.
24 T'pe in the date chec) program, compile, and e+ecute the program. Test the program on a
series of different input values.
E3
:hapter 1 K 9ooping
34 8rite a program to calculate the range that a (all would travel when it is thrown with an initial
velocit' v
)
and angle *. >ased on an initial velocit' provided (' the user, calculate the range
ever' 5 degrees for angles (etween 5 and C5 degrees. .f we assume negligi(le air friction and
ignore the curvature of the earth, a (all that is thrown into the air from an' point on the earths
surface will follow a para(olic flight path.
The range 3distance
(etween the initial origin and
final impact4 is determined (' the formula$
range =
2v
,
2
g
co$ * $in*
where v
)
is the initial velocit' of the (all, ` is the angle of the throw, and g is the acceleration
due to the earth7s gravit'. The value for gravit' should (e defined as a constant and set to 61.C1
meters per second.
+ote, the intrinsic trigonometric functions wor) in radians, so the angle in degrees will need to
(e converted to radians for the calculations. To convert degrees to radians$
radians = degrees
(

1*,
)
Test the program on a series of different input values.
E<
Origin "m&act
*ime
``
:hapter 1 M 9ooping
1; Formatted In"ut7&ut"ut
0ortran uses a 0=*I,T statement to allow control on how data is displa'ed or read. This is useful
when ver' specific input or output is reAuired. 0or e+ample, displa'ing mone' figures t'picall' reAuire
e+actl' two decimal places. There are format specifiers for each data t'peP integer, real, character,
logical, and comple+.
1;.1 Format
The format specifiers, separated (' commands, are contained in a pair of parenthesis. There are
multiple possi(le wa's to define a format. However, we will focus on the easiest, most direct method.
The format specifier will replace the second -Y2 in the read or write statements. 0or e+ample$
read (*,'(<format specifiers>)') <variables>
write (*,'(<format specifiers>)') <variables/expressions>
The following sections e+plain the options for the format specifiers.
1;. Format '"ecifiers
The format specifiers tell the s'stem e+actl' how the input or output should (e handled. Each value
(eing read or written reAuires some amount of space. 0or e+ample, an integer of four digits reAuires at
least four spaces or positions to print. Therefore, the num(er of positions to (e used is a )e' part of the
specifier.
The following convention of s'm(ols$
w + the num(er of positions to (e used
m + the minimum num(er of positions to (e used
d + the num(er of digits to the right of the decimal point
n Q the num(er or count
r + repeat count
The following is a summar' of the most commonl' used format specifiers$
De$cription Speci:ier
.ntegers rIw or rIw.m
*eal rFw.d
9ogicals r+w
:haracters r. or r.w
E5
:hapter 10 K 0ormatted .nput5=utput
Hori@ontal /ositioning 3space4 nG
Hori@ontal /ositioning 3ta(4 1n
Vertical %pacing -
.n addition, each specifier or group of specifiers can (e repeated (' preceding it with a repeat count.
0ormat specifiers for comple+ num(ers will (e addressed in later chapters.
1;.! Integer Format '"ecifier
The integer format specifier rIw or rIw.m is used tell the s'stem e+actl' how man' positions should (e
used to either read or write an integer varia(le. The w is the width or how man' total places are used.
.f the num(er is negative, the sign uses a place. The m is optional and can (e used to set a minimum
num(er of digits to displa', which will displa' leading @ero7s if needed in order to displa' the minimum
num(er of digits. The r is the num(er of times the format specifier should (e repeated.
, format of 73iE47 would loo) li)e$
x x x x x x
, w +
0or e+ample, given the declarations,
integer :: num1=42, num2=123, num3=4567
the following write statement can (e used to displa' the value in varia(le num1 with no leading or
trailing spaces.
write (*,'(i2)') num1
8hich will displa' -<22.
Iultiple varia(les can (e displa'ed. 0or e+ample, to displa' the values in varia(les num1 and num2,
with no leading or trailing spaces.
write (*,'(i2,i3)') num1, num2
8hich will displa' -<21232 with no spaces (etween the two different values. However,
write (*,'(i2,i4)') num1, num2
will displa' -<2 1232 with one space (etween the values. 0urther,
write (*,'(3(i5))') num1, num2, num3
will displa' - <2 123 <5EB2 where each varia(le uses < spaces.
EE
:hapter 10 M 0ormatted .nput5=utput
1;.$ +eal Format '"ecifier
The real format specifier r-w.d is used tell the s'stem e+actl' how man' positions should (e used to
either read or write an real varia(le. The w is the width or how man' total places are used, including
the decimal point. .f the num(er is negative, the sign uses a place. The d is how digits are displa'ed
after the decimal point, which does not count the decimal point. The r is the num(er of times the
format specifier should (e repeated.
, format of 73fE.247 would loo) li)e$
x x x . x x
, d +
, w +
0or e+ample, given the declarations,
real :: var1=4.5, var2=12.0, var3=2145.578
the following write statement can (e used to displa' the value in varia(le 'ar1 with no leading or
trailing spaces.
write (*,'(f3.1)') var1
8hich will displa' -<.52. Iultiple varia(les can (e displa'ed. 0or e+ample, to displa' the values in
varia(les 'ar1 and 'ar2, with no leading or trailing spaces.
write (*,'(f5.2,f8.3)') var1, var2
8hich will displa' - <.50 12.0002 with no leading spaces.
write (*,'3(f10.4))') var1, var2, var3
8hich will displa' - <.5000 12.0000 21<5.5BC02 where each varia(le uses 10 spaces with each
having e+actl' < digits after the decimal point.
,lthough we ma' print a num(er using as man' positions as 'ou want, this is onl' for input5output
formatting. The num(er of positions or si@e is not the precision 3i,e,, the num(er of significant digits4
of that num(er. The default precision of real num(ers is a(out seven significant digits. This is the
precision of real num(ers. However, we can print a real num(er using 50 positions in which 25
positions are for the fractional part. This is onl' a wa' of descri(ing the appearance and does not
change the precision of real num(ers.
1;.5 Logical Format '"ecifier
The logical format specifier rLw is used tell the s'stem e+actl' how man' positions should (e used to
either read or write an logical varia(le. The w is the width or how man' total places are used. The r is
the num(er of times the format specifier should (e repeated. %ince a logical varia(le can onl' (e set to
the logical constants .true. or .false. the width will specif' how man' of the characters logical
constants will (e read or displa'ed.
EB
:hapter 10 K 0ormatted .nput5=utput
0or e+ample, given the declarations,
logical :: dooropen=.true., windowopen=.false.
the following write statement can (e used to displa' the value in varia(le 'ar1 with no leading or
trailing spaces.
write (*,'(l1,1x,l1)') dooropen, windowopen
8hich will displa' -T 02. +ote, the &1 format is lower6case 9 and num(er 1.
The si@e or width can (e adFusted as needed. 0or e+ample, the following write statement,
write (*,'(l4,2x,l5)') dooropen, windowopen
will displa' -True 0alse2 3with two spaces4.
1;.0 Character Format '"ecifier
The real format specifier rw is used tell the s'stem e+actl' how man' positions should (e used to
either read or write a character varia(le. The w is the width or how man' total places are used. .f the
width is not specified, the e+isting length of the string is used. The r is the num(er of times the format
specifier should (e repeated.
, format of 73aE47 would loo) li)e$
c c c c c c
, w +
0or e+ample, given the declarations,
character(len=11) :: msg = "Hello World"
the following write statement can (e used to displa' the string in varia(le msg with no leading or
trailing spaces.
write (*,'(a7)') msg
8hich will displa' -Hello 8orld2. Iultiple varia(les or strings can (e displa'ed. 0or e+ample, to
displa' the string in varia(le msg and the string -ood ('e cruel world2.
write (*,'(a7,2x,a)') msg, "Good bye cruel world"
8hich will displa' -ood ('e cruel world2 to the screen.
1;.5 %d)ance Clause
The advance clause instructs the computer whether or not to advance the cursor to the ne+t line. The
possi(le values are -'es2 and -no2. .f the advance clause is not included, the default value is -'es2.
This clause can is useful when prompting for user input to allow the input to (e entered on the same
line as the prompt.
EC
:hapter 10 M 0ormatted .nput5=utput
0or e+ample, the period program from the previous chapter included the statements$
! prompt for and read the n value
write(*,*) "Enter N value: "
read(*,*) n
8hich, when e+ecuted, the input is entered on the line following the prompt.
c:\mydir> sums
Example Program
Difference between sum of squares
and square of sums
Enter count of numbers to read:
3
Difference: 2640
8hen the advance clause is included, with the setting of -no2 as follows$
! prompt for and read the n value
write(*,*, advance="no") "Enter N value: "
read(*,*) n
The resulting e+ecution would (e as follows$
c:\mydir> sums
Example Program
Difference between sum of squares
and square of sums
Enter count of numbers to read: 10
Difference: 2640
8hich allows the input to (e entered on the same line as the prompt.
1;.8 ,xam"le
This e+ample will read a date from the user 3month, date, and 'ear, on the same line4, determine the
da' of wee) 3for that month5date5'ear4. Then, the program will displa' the original input date 3numeric
form4 and the formatted date. The original input date will (e displa'ed include leading 07s 3i.e.,
01501520104.
1;.6.1 8n'erstan' the Problem
0or this pro(lem, we will read the three num(ers for the date from the user. The verification of the date
information is left as an e+ercise.
E1
:hapter 10 K 0ormatted .nput5=utput
To calculate the da' on which a particular date falls, the following algorithm ma' (e used 3the divisions
are integer divisions4$
a = (14 - month) / 12
y = year - a
m = month + 12*a - 2
daynum = [ date + y + y/4 - y/100 + y/400 + (31*m/12) ] mod 7
The value of da#num is 0 for a %unda', 1 for a Ionda', 2 for a Tuesda', etc.
1;.6.2 Create the 2lgorithm
0or this pro(lem, first we will need to read the date. The verification of the date entered and error
chec)ing is left as an e+ercise. Then, the original input date can (e displa'ed, in numeric form,
formatted appropriatel'. 0or a date, this would mean two digits for the month, a -52, two digits for the
date, a -52, and four digits for the 'ear. 8hen the date is onl' one digit, for e+ample 5, it is customar'
to displa' a -052 so the program will ensure this occurs.
! declare variables
! integer -> month, date, year
! display initial header
! prompt for month, date, and year
! read month, date, and year
! display formatted numeric month/date/year
Then the program can calculate the da' of the wee) 3(ased on the formula4 and convert the resulting
num(er 306E4 into a date string and displa' the result.
! calculate day of week
! convert day of week (0-6) to string
! convert month (1-12) to string
! display formatted string for day, month, and year
0or convenience, the steps are written a program comments.
1;.6.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program dateformatter
! declare variables
implicit none
integer :: month, date, year
integer :: a, m, y, d,
character(9) :: amonth, day_of_week
! ----------
! display initial header
write(*,*) "Date Formatting Example"
B0
:hapter 10 M 0ormatted .nput5=utput
! prompt for month, date, and year
write(*,*,advance="no") "Enter date (month, date, year):"
! read month, date, and year
read (*,*) month, date, year
! ----------
! display formatted numeric month/date/year
write(*,*) "----------------------------------------"
write(*,*) "Input Date: "
write(*,'(5x, i2.2, a, i2.2, a, i4)', imonth, "/", &
idate, "/", iyear
! ----------
! calculate day of week
a = (14 - imonth) / 12
y = iyear - a
m = imonth + 12 * a - 2
d = mod ( (idate + y + y/4 - y/100 + y/400 + (31*m/12)), 7)
! ----------
! convert day-of-week integer to day-of-week string
select case (d)
case (0)
day_of_week = "Sunday "
case (1)
day_of_week = "Monday "
case (2)
day_of_week = "Tuesday "
case (3)
day_of_week = "Wednesday"
case (4)
day_of_week = "Thursday "
case (5)
day_of_week = "Friday "
case (6)
day_of_week = "Saturday "
end select
! ----------
! convert month (1-12) to string
select case (month)
case (1)
amonth = "January "
case (2)
amonth = "February "
case (3)
amonth = "March "
case (4)
amonth = "April "
B1
:hapter 10 K 0ormatted .nput5=utput
case (5)
amonth = "May "
case (6)
amonth = "June "
case (7)
amonth = "July "
case (8)
amonth = "August "
case (9)
amonth = "September"
case (10)
amonth = "October "
case (11)
amonth = "November "
case (12)
amonth = "December "
end select
! ----------
! display formatted string for day, month, and year
write(*,'(/a)') "Formatted Date:"
write(*,'(5x, a, a, a, 1x, i2.0, a, i4/)') &
trim(day_of_week), ", ", trim(smonth), &
idate, ", ", iyear
end program dateformatter
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le. The
trim)* intrinsic function removes an' trailing spaces from the input string. ,dditional information
regarding handling character data t'pes in provided in the following section.
1;.6.4 0est9Debug the Program
0or this pro(lem, the testing would (e to ensure that the output formatting is correct. %ince there is no
error chec)ing on the input, onl' correct dates should (e entered. Test the program on a series of
different input values and verif' that the output is correct for those input values.
1;.9 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
1;.:.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat is the format specifier for each of the following$
a4 integer values
(4 real values
c4 logical values
d4 hori@ontal spacing 3i.e., spaces4
B2
:hapter 10 M 0ormatted .nput5=utput
e4 a newline
f4 characters5strings
24 ;escri(e the output of the following code fragment 31 pts each4$
+ote, show (lan)s with an R 3underscore4 character.
write (*,'(a5)') "Hello World"
write (*,'(a)') "Hello World"
34 ;escri(e the output of the following code fragment 33 pts4$
!ote, show (lan)s with an R 3underscore4 character.
integer :: number = 5
write (*,'(i5.3)') number
<4 8hat is the write statement and format specifier to output the integer varia(le num1 which
contains an value (etween 0 and 111 3right Fustified, no leading @ero7s, no additional spaces4.
54 8hat is the write statement and format specifier to output the real value of pi which has (een
initiali@ed to 3.1<151 3right Fustified, no additional spaces4N
E4 8hat is the single write statement and format specifier to output L/rogrammingL and L.s 0un\L
on two different linesN
B4 8hat is the single write statement and format specifier to output LEnter !um(er$L and leave the
cursor on the current lineN
1;.:.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the date formatting program e+ample, compile, and e+ecute the program. Test the
program on a series of different input values and verif' that the output is correct for those input
values.
24 "pdate the date formatting program to perform complete error chec)ing on the date entered.
That is, the program should chec) for appropriate values for month 3(etween 1 and 124, chec)
for appropriate values for date 3(etween 1 and 314, including chec)ing for a valid date for the
specific month, and ensure that the value for 'ear is (etween 11B0 and 3000 3inclusive4. 0or
e+ample, ,pril 31 is not a valid date. ,dditionall', the program should chec) for a leap 'ear to
see if 0e(ruar' has 2C or 21 da's for that 'ear. Test the program on a series of different input
values and verif' that the output is correct for those input values.
B3
:hapter 10 K 0ormatted .nput5=utput
34 8rite a 0ortran program that displa's an amorti@ation schedule. The program should read the
loan amount, annual interest rate, and the loan term in months 3from a single line4.
The formula for calculating the monthl' pa'ment is$
pa#ment = amount irate
(1+irate)
term
( (1+irate)
term
1)
+ote, the irate in the formula must (e converted to a monthl' rate 3divided (' 124 and then
divided (' 100 3to convert from percentage4. ;uring the time period 3term4, some of each
monthl' pa'ment will (e used to pa' the interest and some will (e used to reduce the
outstanding (alance. The monthl' interest amount can (e calculated (' monthl' interest rate
times outstanding (alance. The amounts must (e lined up with onl' two digits for cents. The
pa'ment num(er must three digits 3including leading @ero7s if necessar'4. Test the program on a
series of different input values and verif' that the output is correct for those input values.
<4 8rite a 0ortran program that calculates and displa's compounded interest. The program should
read the initial principal amount, interest rate percentage, and the term 3num(er of 'ears4. The
program should displa' a summar' of the input and the 'earl' compounded interest. *efer to
the e+ample output for formatting.
The formula for compounding interest is$
value = principal (1+interest )
#ear
+ote, the interest rate percentage read form the user must (e converted to a num(er 3i.e.,
divided (' 1004. The output must (e formatted in a manner similar to the e+ample output. This
includes ensuring that the dollar amounts are displa'ed with the appropriate two decimal points.
Test the program on a series of different input values and verif' that the output is correct for
those input values.
B<
11 Characters and 'trings
0ortran was originall' developed for scientific and engineering application reAuiring significant
mathematical calculations. However, the 0ortran 15 language includes e+tensive character and string
handling capa(ilities.
11.1 Character and 'tring Constants
, character is a single character or s'm(ol, t'picall' enclosed in Auotes. 0or e+ample, letters 3-,262W2
and -a2 6 -@24, punctuation 3-\2, -,2, -N2, etc.4 , s'm(ols, 3-S2, -a2, -[2, etc.4, and digits -12, -22 are
characters.
%ome e+amples include$
"X"
"z"
"5"
:haracter and string constants are case sensitive. %o, character -J2 3upper6case4 is not the same as -+2
3lower6case4. 8hen a digit is enclosed in Auotes, it is treated as a character and conseAuentl'
arithmetic operations 3addition, su(traction, etc.4 are not allowed.
, string is a series of characters. , string consists of an ar(itrar' seAuence of characters also enclosed
in Auotes. %ome e+amples include$
"Hello World."
"456"
"1 2 3"
"456?"
"Good bye cruel world!!"
"Have a nice day?"
%ince digits enclosed in Auotes are not numeric values, the strings -1 2 32 and -<5EN2 are allowed.
, pro(lem arises if 'ou want to have a Auote in the string itself. , dou(le Auote will (e interpreted as a
single within a string.
"He said ""wow"" when he heard"
The dou(le6Auoting is sometimes referred to as an escape character. %trings and characters must (e
associated with the character data t'pe.
11. Character 3ariable #eclaration
, character varia(le is a varia(le that can contain a set of 1 or more characters. :haracter varia(les
must have a defined length. ,ll declarations are placed in the (eginning of the program 3after the
program statement4. ;eclaring character varia(les formall' defines the t'pe and sets aside memor'.
B5
:hapter 11 K :haracters and %trings
This is performed with a t'pe declaration statement in the form of$
<type> :: <list of variable names>
0or character varia(les, the t'pe is -character2. 0or e+ample, to define an character varia(le to hold the
da' of wee) 3i.e., -8ednesda'24, the following declaration,
character(len=9) :: dayofweek
8ould define the varia(le, da%o("ee-, with a ma+imum length of 1 possi(le characters.
,dditional e+amples include$
character(len=3) :: symbol1, symbol2
character :: symbol3
character(1) :: symbol5, symbol5
character(30) :: symbol6, symbol7
The declarations can (e entered in an' order, however the' must (e at the (eginning of the program.
The -lenU2 is optional and can (e omitted. 8hen the length is omitted entirel', the default length is set
to 1. This, -character2, -character3lenU14, and -character3142 are all the same.
8hen multiple varia(les are included in a single declaration, the' must all (e the same length. .f
different lengths are reAuired, separate declaration lines are reAuired.
11.! Character 3ariable Initiali(ation
.t is possi(le to declare a character varia(le and to set it is initial value at the same time. This
initiali@ation is not reAuired, (ut can sometime (e convenient. 0or e+ample, to define an character
varia(le, da%o("ee-, and set it to a da' of wee)$
character(len=9) :: todaysdate="Wednesday"
,dditional e+amples include$
character(9) :: thismonth="June", lastmonth, nextmonth="July"
character :: ltr1="A", ltr2="b"
%paces or no spaces (etween the varia(les, eAual signs, semicolons, and commas are allowed.
Varia(les initiali@ed at declaration can (e changed during program e+ecution as needed.
11.$ Character Constants
.t is possi(le to declare a character varia(le, set it is initial value, and ensure that the value can not (e
changed. 0or e+ample, to define an character constant, lang,
character(len=7), parameter :: lang="English"
To save counting the characters, the -Y2 can (e used. 0or e+ample,
character(len=*), parameter :: university="UNLV"
This instructs the 0ortran compiler to count the characters and set the appropriate length.
BE
:hapter 11 M :haracters and %trings
11.5 Character %ssignment
,ssignment is term for setting a character varia(le eAual to some value 3character or string4.
,ssignment is performed with a eAual 3U4 sign. 0or e+ample, given the declaration,
character(9) :: thismonth
, value can (e assigned to the varia(le as follows,
thismonth = "September"
8hen character varia(les are assigned the' are filled from the left and automaticall' padded with
(lan)s if necessar'. 0or e+ample, if the varia(le thismonth is reset
thismonth = "May"
The varia(le thismonth contains -Ia' 2 3i.e., -Ia'2 with an additional E (lan)s4.
11.0 Character &"erators
The onl' character operator is -552 3concatenation4 which simpl' concatenates two strings together. 0or
e+ample,
"University of" // "Nevada Las Vegas"
:haracters varia(les and literals ma' (e used with concatenation. 0or e+ample, given the following
declaration,
character(len=6) :: str1="ABCDEF", str2="123456"
character(len=12) :: str3
The following statements
str3 = str1 // str2
will set str& to -,>:;E0123<5E2.
11.5 Character 'ubstrings
, su(string is a su(set of a string. , su(string can (e selected (ased on the characters position or count
within the start with the first character corresponding to 1 and the second character corresponding to 2
as so forth for as man' characters are in the entire string. The su(string is specified with a start and
stop position in the form of 3start$stop4. The stop must (e greater than or eAual to the stop position.
0or e+ample, given the following declaration,
character(len=6) :: str1="ABCDEF", str2="123456", str3
The following statements
str3 = str1(1:3) // str2(4:6)
will set str& to -,>:<5E2.
BB
:hapter 11 K :haracters and %trings
11.8 Character Com"arisons
The standard relational operators 3-UU2, -[2, -[U2, etc.4 have some limitations when character data is
used. %imple comparisons, such as,
"A" < "D"
"ABC" == "ABC"
will wor) as e+pected. That is, (oth will evaluate to true.
However, when comparing, the following characters,
"A" > "a"
"100" < "20"
"ABC" <= "ABCD"
each will evaluate to false.
This is a result of the relational operations referring to the assigned values 3(ased on their location in
the ,%:.. ta(le located in ,ppendi+ ,4.
:omparisons (etween digits, -02 6 -12, will wor) relative to each other. :omparisons (etween upper6
case letters, -,2 6 -W2, will also wor) relative to each other. :omparisons (etween lower6case letters,
-a2 6 -@2, will also wor) relative to each other. %ince the lower case letters are after the upper case
letters in the ta(le an upper6case letter will (e greater than a lower6case letter. The digits are in the
ta(le (efore letters 3upper and lower6case4, so the' will evaluate as less than letters. This must (e ta)en
into account when dealing with character comparisons.
11.9 Intrinsic Character &"erations
There are a num(er of character oriented intrinsic operations. %ome of the (asic character oriented
functions include$
Function De$cription
,:H,*3.4 *eturns the character represented (' integer argument .
(ased on the ,%:.. ta(le 3,ppendi+ ,4. .nteger argument .
must (e (etween 1 and 12B.
.,:H,*3:4 *eturns the integer value of the character argument :
represented (' ,%:.. ta(le 3,ppendi+ ,4.
9E!3%T*4 *eturns an integer value representing the length of string
argument %T*.
9E!RT*.I3%T*4 *eturns an integer value representing the length of string
argument %T* e+cluding an' trailing spaces.
T*.I3%T*4 *eturns string (ased on the string argument %T* with an'
trailing spaces removed.
, complete list of intrinsic functions can (e found in ,ppendi+ ;.
BC
:hapter 11 M :haracters and %trings
11.1; ,xam"le
This e+ample will scan a string and convert all lower6case letter to upper6case.
11.1;.1 8n'erstan' the Problem
0or this pro(lem, the string will (e read from the user with a ma+imum of C0 characters. ,n' lower
case letters encountered will (e converted to upper6case. ,ll other characters 3digits, s'm(ols, etc.4
will (e left alone. To determine if a characters is lower6case, we can see if it is (etween -a2 and -@2.
The final string will (e displa'ed (ac) to the screen. >ased on the ,%:.. ta(le in ,ppendi+ ,, there is
a specific, fi+ed difference (etween each upper and lower6case letter. Thus, in order to convert a lower6
case character to upper6case, that difference can (e su(tracted. However, in order to perform the
su(traction, each character needs to (e converted into an integer 3(ased on its value in the ,%:.. ta(le4.
The .,:H,*34 intrinsic function performs this conversion. ,fter the conversion 3su(traction4, the
integer must (e converted (ac) into its corresponding character, which can (e accomplished with the
,:H,*34 intrinsic function. These functions wor) on a single character5integer, so each character will
need to (e addressed individuall'.
11.1;.2 Create the 2lgorithm
0or this pro(lem, first we will need to prompt for and read the input string. Then an' trailing (lan)s
will (e removed and the final length can (e determined. >ased on that length, each character will (e
accessed and converted if needed.
! declare variables
! integer -> string1, string2, I, strlen
! display initial header
! prompt for string
! read string
! trim any trailing blanks
! determine length of string
! loop
! access each character
! if check lower-case ("a" "z") -> convert to upper-case
! display final string
0or convenience, the steps are written a program comments.
11.1;.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program caseconverter
! declare variables
implicit none
integer :: i, strlen
character(80) :: string1
B1
:hapter 11 K :haracters and %trings
! ----------
! display initial header
write(*,'(a,/)') "Case Conversion Example"
! ----------
! prompt for string
! read string
write(*,'(a)',advance="no") "Enter String (80 char max): "
read (*,'(a)') string1
! ----------
! trim any trailing blanks
! determine length of string
strlen = len(trim(string1))
! loop
do i = 1, strlen
! access each character
! if check lower-case -> convert to upper-case
if ( string1(i:i) >= "a" .and. string1(i:i) <= "z" ) then
string1(i:i) = achar( iachar(string1(i:i)) - 32)
end if
end do
! ----------
! display final string
write(*,'(/,a)') "-------------------------------------"
write(*,'(a,/,2x,a,/)') "Final String: ", string1
end program caseconverter
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
11.1;.4 0est9Debug the Program
0or this pro(lem, the testing would ensure that the output string is correct for the given input.
0or e+ample, the following output,
c:\mydir> case
Case Conversion Example
Enter String (80 char max): Hello World!?
-------------------------------------
Final String:
HELLO WORLD!?
Each lower6case letter was converted to upper6case while the upper6case, space, and punctuation were
unchanged. The program should (e e+ecuted with a series of test inputs to verif' the correct output.
C0
:hapter 11 M :haracters and %trings
11.11 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
11.11.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat is the declaration for a character varia(le to contain the string -Hello 8orld2N
24 iven the following relational e+pressions,
"D" > "c"
"100" < "20"
"Da" > "cA"
"20" < "10"
"d" > "C"
"20" < "100"
"ABBC" <= "ABCD"
state which will evaluate to true and which to false.
34 iven the following 0ortran statements,
character(len=*) :: str1="abcdef", str2="ABCDEF"
character(len=*) :: str3="123456", str4="78910"
character(len=12) :: astr1, astr2, astr3, astr4
astr1 = str1(1:3)
astr2 = str3(4:6)
astr3 = str3 // str4
astr4 = str2(4:6) // str3(1:3) // str1(2:3)
provide the resulting strings 3astr1 D astr<4.
<4 How can the integer value 3(ased on the ,%:.. ta(le4 of a character (e o(tainedN
54 How can integer value (e converted to a character 3(ased on the ,%:.. ta(le4N
11.11.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the case conversion e+ample program e+ample, compile, and e+ecute the program. Test
the program on a series of different input values and verif' that the output is correct for those
input values.
24 "pdate the case conversion e+ample program to convert an' upper6case characters to lower6
case characters. Test the program on a series of different input values and verif' that the output
is correct for those input values.
C1
:hapter 11 K :haracters and %trings
34 8rite a program to read a string and count the vowels 3-a2, -e2, -i2, -o2, and -u24. The
program should provided a count for each vowel and a total count of vowels. The program
should ensure that the vowels are counted for (oth upper and lower6case. Test the program on a
series of different input values and verif' that the output is correct for those input values.
<4 8rite a program to read 5 strings 3_ C0 characters each4 and displa' the strings in alpha(etical
order. Test the program with a variet' of different input strings, including digits, upper6case,
and lower6case characters. Test the program on a series of different input values and verif' that
the output is correct for those input values.
C2
1 File &"erations
0ile operations allow 0ortran programs to read from files and5or write to files. The (asic read and write
statements for file operations are the same as previousl' used with some additional information or
clauses.
1.1 File &"en
, file must (e opened (efore information can (e written or read from a file. .n order to open a file, the
operating s'stem needs some information a(out the file in order to correctl' identif' the file and
esta(lish the access parameters 3i.e., read, write, etc.4. The open statement -clauses2 is how is
information is provided.
The file open statement is as follows$
open (unit=<unit number>, file=<file name>, &
status=<file status>, action=<file action>, &
position=<file position>, iostat=<status variable>)
The following ta(le summari@es the various open statement clauses.
C&au$e %'p&anation
unit "nit num(er for su(seAuent file operations 3i.e.,
read, write, etc.4. T'picall' an integer (etween 10
and 11.
:i&e !ame of file to (e opened. :an (e Auoted or a
character varia(le.
$tatu$ %tatus of file. ,llowa(le options -old2, -new2, or
-repalce2
-old2 Q the file must alread' e+ist.
-new2 Q a new file will (e created.
-replace2 Q a new file will (e created,
replacing an e+isting one if necessar'.
action ,ction or open operation. ,llowa(le options are
-read2, -write2, or -readwrite2.
-read2 Q read data from a file.
-write2 Q write data to a file.
-readwrite2 Q simultaneousl' read data from
and write data to a file.
po$ition /osition or place to start. ,llowa(le options are
-rewind2 3(eginning4, -append2 3end4.
C3
:hapter 12 K 0ile =perations
io$tat !ame of varia(le for s'stem to place a status code
indicating the status 3success or failure4 of the
operation. .f the status varia(le is set to 0, the
operation is successful. .f the status varia(le is set
to [0, an error occurred and the operation was
unsuccessful.
The unit num(er assigned should (e (etween 10 and 11.
1. File Write
The file must (e opened for -write2 or -readwrite2 access (efore an' information can (e written to the
file. The general form of the write statement is as follows$
write (unit=<unit number>, fmt=<format statement>, &
advance="no", iostat=<variable>) &
<variables/expressions>
The write is the same as the simple write, however the unit num(er must (e the num(er assigned
during the open operation. !ormall', the ne+t write will (e on the ne+t line. The -advanceU2no22 is
optional. .f it is included, the ne+t write will (e on the same line where the previous line stopped.
0or e+ample to open a file named temp.t+t and place the string -0ortran E+ample2 and the num(ers <2,
and 3.1<151 on separate lines, the following declarations$
integer :: myanswer=42, myopenstatus, mywritestatus
real, parameter :: pi=3.14159
character(15) :: mymessage="Fortran Example"
character(8) :: myfilename="temp.txt"
and the following 0ortran statements,
open (unit=10, file=myfilename, status="replace", &
action="write", position="rewind", &
iostat=myopenstatus)
if (myopenstatus > 0) stop "Can not open file."
write(10, '(a/, i5/, f7.5)', iostat=mywritestatus) &
mymessage, myanswer, pi
would write the file information to the file.
1.! File +ead
The file must (e opened for -read2 or -readwrite2 access (efore an' information can (e read from the
file.
C<
:hapter 12 M 0ile =perations
The general form of the write statement is as follows$
read (unit=<unit number>, fmt=<format statement>, &
iostat=<variable>) <variables/expressions>
The read is the same as the simple read, however the unit num(er must (e the num(er assigned during
the open operation. .f the status varia(le is set to less than 0, that is an indication that the end of the file
has (een reached.
0or e+ample, if the file num(ers.dat e+ists and has two num(ers 3on separate lines4, the following
declarations,
integer :: num1, num2, myopenstatus, myreadstatus
character(11) :: myfilename="numbers.txt"
and the following 0ortran statements,
open (unit=12, file=myfilename, status="old", &
action="read", position="rewind", &
iostat=myopenstatus)
if (myopenstatus > 0) stop "Can not open file."
read(12, '(i5)', iostat=myreadstatus) num1
read(12, '(i5)', iostat=myreadstatus) num2
would write the file information to the file.
1.$ +e*ind
,n open file can (e reset (ac) to the (eginning. This might (e useful if the file needs to (e read twice.
The rewind statement will reset the file read pointer and su(seAuent reads will start (ac) at the
(eginning. The general form of a rewind statement is$
rewind(<unit number>)
8here the the unit num(er was assigned during the initial open. The file must (e open for the rewind
to wor) correctl'.
1.5 2ac/s"ace
8hen reading from a file, each successive read will return the ne+t line from the file. The computer
)eeps trac) of which lines have (een read and will automaticall' return the ne+t line. .t is possi(le to
read a line and then (ac)space and re6read the line again with the (ac)space statement.
The general form of a (ac)space statement is$
backspace(<unit number>)
8here the the unit num(er was assigned during the initial open. The file must (e open for the
(ac)space to wor). This is not used ver' often.
C5
:hapter 12 K 0ile =perations
1.0 Close File
,n open file should (e closed when it is no longer needed. The general form of a close statement is$
close(<unit number>)
8here the the unit num(er was assigned during the initial open.
0or the previous e+amples,
close(10)
close(12)
would (e used to close the opened files.
1.5 ,xam"le
.n this e+ample we will write a 0ortran program to read an input file and write a line num(er and the
original line to an output file.
12.5.1 8n'erstan' the Problem
0or this pro(lem, we will read get the file names from the user and open the files. Then we will read a
line from the input file, and write the line num(er and line to the output file. 8hen done, we will close
the file.
12.5.2 Create the 2lgorithm
0or this pro(lem, first we will need to prompt for and read the file names from the user and ensure that
the' open correctl'. .f the file can not (e opened, an error message will (e displa'ed and the file names
will (e re6read.
! declare variables
! integer -> i, rdopst, wropst
! character -> line
! display initial header
! loop
! prompt for input file name
! read input file name
! open input file (read access)
! if open unsuccessful, display error message
! otherwise, end loop
! loop
! prompt for output file name
! read output file name
! open output file (write access)
! if open unsuccessful, display error message
! otherwise, end loop
=nce the file is open, a line will (e read from the input file, and the line num(er and the line will (e
CE
:hapter 12 M 0ile =perations
written to the output file. 0or this e+ample, we will assume that a line will have 132 or less characters.
This process will continue until there are no more lines in the input file.
! loop
! read line from input file
! if end of file, exit loop
! write line number and line to output file
! close files
0or convenience, the steps are written a program comments.
12.5.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program linenumbers
! declare variables
implicit none
integer :: i, rdopst, wropst, rdst
character(30) :: rdfile, wrfile
character(132) :: line
! display initial header
write(*,*) "Line Number Example"
! ----------
! prompt for input file name
do
write(*,'(a)', advance="no") "Input File Name: "
! read input file name
read(*,*) rdfile
! open input file (read access)
! if open unsuccessful, display error message
! otherwise, end loop
open(12, file=rdfile, status="old", &
action="read", position="rewind", &
iostat=rdopst )
if (rdopst==0) exit
write(*,'(a/,a)') "Unable to open input file.", &
"Please re-enter"
end do
! ----------
! prompt for output file name
do
write(*,'(a)', advance="no") "Output File Name: "
! read output file name
CB
:hapter 12 K 0ile =perations
read(*,*) wrfile
! open output file (read access)
! if open unsuccessful, display error message
! otherwise, end loop
open(14, file=wrfile, status="replace", &
action="write", position="rewind", &
iostat=wropst )
if (wropst==0) exit
write(*,'(a/,a)') "Unable to open output file.", &
"Please re-enter"
end do
! ----------
i = 1
do
! read line from input file
read(12, '(a)', iostat=rdst) line
! if end of file, exit loop
if (rdst >0) stop "read error"
if (rdst <0) exit
! write line number and line to output file
write(14, '(i10,2x,a)') i, line
i = i + 1
end do
! close files
close(12)
close(14)
end program linenumbers
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
12.5.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the program with various input files and
verif'ing that the line num(ers are correctl' added.
1.8 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
CC
:hapter 12 M 0ile =perations
12.6.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat must occur (efore a file can (e read or writtenN
24 8hat is the range of the valid unit num(ers for a file openN
34 0or the following statements$
integer :: opnstat
character(20) :: filename="file.txt"
open (14, file=filename, status="old", action="read", &
position="rewind", iostat=opnstat)
if ( opnstat > 0 ) then
write (*, *) "Error, can not open file."
stop
end if
a4 8hat is the name of the file (eing openedN
(4 8hat is the unit num(er that will (e used for su(seAuent write operationsN
c4 ;oes the error message get printed if the file does not e+ist 3'es5no4N
d4 8hat does it mean when the status varia(le is [ 0N
<4 ,ssume the file answers.txt e+ists and contains$
"line 1 data1=23 data2 = 34 data3 = 5123"
8hat is the read statement reAuired to get data1, data2, and data3 into the integer varia(les
num1, num2, and num. respectivel'.
12.6.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the line num(ers program, compile, and e+ecute the program. Test the program on a
num(er of different input values.
24 .magine the movement of a small circle that rolls on the outside of a
rigid circle. .magine now that the small circle has an arm, rigidl'
attached, with a plotting pen fi+ed at some point. That is a epic'cloid,
commonl' called a spirograph
B
. 8rite a 0ortran 15 program to
generate the 3+,'4 coordinates for a spirograph drawing.
0irst, the program should prompt for an output file name, read the file name, and open the file.
B 0or more information, refer to$ http$55en.wi)ipedia.org5wi)i5%pirograph
C1
:hapter 12 K 0ile =perations
.f the file can not (e opened, the program should displa' an appropriate error message and re6
prompt. !e+t, the program should prompt for a read radius 1 3fi+ed circle4, radius 2 3moving
circle4, offset position 3rigid arm length4. The radius 1, radius 2, and offset position values must
(e (etween 6100 and O100 3inclusive4. .f an' value is out of range, the program should re6
prompt. .f the user does not enter a valid file name or num(er of input values after three tries,
the program should terminate with an appropriate error message. That is, three errors are
accepta(le, (ut if a fourth error is made, the program should terminate. The prompts and
su(seAuent reads should (e on the same line 3see e+ample4.
Then, the program should generate 3+,'4 points (ased on one the following formulas$

x=((radius
1
+radius
2
) co$( step)) + offsetposition co$
(
(radius
1
+radius
2
)
step
radius
2
)
#=((radius
1
+radius
2
) $in(step)) + offsetposition $in
(
(radius
1
+radius
2
)
step
radius
2
)
The step should start at 0.0 and stop at 3E0.0, stepping (' 0.1. ,ll writes should use a formatted
output 3not the 7Y74. Then the program should close the output file, inform the user the plotting
is completed. Test the program on a num(er of different input values.
34 8rite a 0ortran program that pla's the :haos ame. To pla' the :haos ame, plot 3 points ,,
>, : and an ar(itrar' initial point J1. Then, generate a random num(er (etween 1 and 3
representing ,, >, or :. .f , comes up, plot the midpoint of the line Foining J1 to ,. .f >
comes up, plot the midpoint of the line Foining J1 to >P the case with : is similar. :all this
new point J2. *oll the die again. /lot the midpoint of the line Foining J2 to either ,, > or :
depending on the outcome of the die toss. :all this new point J3. *epeat this process ! times.
Test the program on a num(er of different input values.
&ote, the correct output of this program is shown on the cover page.
10
1! 'ingle #imension %rrays
,n arra' is a collection or set of data. , varia(le can hold a single value. ,n arra' can hold multiple
values. The t'pe 3i.e., integer, real, etc.4 of each item in the arra' must (e the same. .n order to access
specific elements an index or subscript is used. The inde+ specifies which element or value in the
arra'.
,n arra' is consider a direct access structure since an' element can (e accessed directl', without
accessing an' other elements.
The most (asic form of an arra' is a single dimension arra'. , single dimension arra' can (e thought
of as a single column in a spreadsheet. The column name, li)e , is the arra' name and the row
num(er is li)e the inde+.
0or e+ample, a single dimension arra' might loo) li)e$
inde+ value
,rra' !ame 1 Zvalue[
2 Zvalue[
3 . . .
. . .
Zvalue[
n Zvalue[
The specific s'nta+ reAuires an inde+ or su(script to specif' which element of the arra' to access. >'
default, the first element is at inde+U1, the ne+t at inde+U2, and so forth. This can (e changed if
needed.
1!.1 %rray #eclaration
,n arra' must (e declared (efore use. The t'pe of the arra' is defined followed (' the si@e or
dimension. There are two wa's to declare an arra'P static and d'namic.
13.1.1 tatic Declaration
, static declaration means that the si@e or dimension of the arra' must (e defined initiall' 3(efore the
program is compiled4. The si@e definition can not (e altered. The general form an arra' declaration is,
type, dimension(extent) :: name1, name2, , nameN
where t'pe is the data t'pe 3integer, real, etc.4 of the arra'. The dimension specifies the the e+tent or
si@e, and name1, name2, b, name& are names of one or more arra's (eing declared.
11
:hapter 13 K %ingle ;imension ,rra's
0or e+ample, to declare an arra' of 1000 integers,
integer, dimension(1000) :: nums1
will create an arra', nums1, with space for 1000 integer values.
.n this e+ample the e+tent is 1000 which means that the arra' inde+es will range form 1 to 1000. The
e+tent can (e changed (' specif'ing the e+tent as$
smaller-integer :: larger-integer
8hen onl' one num(er is specified, the smaller6integer is assumed to (e 1. 8hen (oth num(ers are
specified, the arra' inde+7s will range (etween the smaller6integer and the larger6integer. 0or e+ample,
a declaration of$
integer, dimension(-5:5) :: ranges
will create an arra', ranges, with inde+es (etween 65 and 5 3inclusive4. "sing inde+ values not within
the specified range will result in an error.
13.1.2 tatic 2rray Declaration
%tatic arra' declarations are appropriate when the ma+imum si@e of the arra' is )nown ahead of time.
=nce the arra' is declared, the si@e can not (e e+tended. , static arra' is initiali@ed and the si@e of set
during the declaration. 0or e+ample, to declare an arra' named costs with < elements and set the four
elements to 10.0, 15.0, 20.0, and 25.0,
real, dimension(4) :: costs=(/10.0, 15.0, 20.0, 25.0/)
The num(ers, enclosed (etween the -52s are assigned in order. %o, costs314 is set to 10.0, costs324 is set
to 15.0, costs334 is set to 20.0, and costs3<4 is set to 25.0.
,dditionall', after declaration, it is possi(le to initiali@e all elements of an arra' to a single value with
an assignment statement. 0or e+ample,
costs = 0
will set all four elements of the costs arra' to @ero.
13.1.3 Dynamic 2rray Declaration
, d'namic declaration means that the si@e or dimension of the arra' can (e set when the program is
e+ecuted. ;'namic arra' declarations are appropriate when the ma+imum si@e of the arra' is not
)nown ahead of time and can (e determined (ased on information o(tained when the program is
e+ecuting. However, once set, the si@e can not (e altered. 8hen using a d'namic declaration, the arra'
t'pe and name must (e defined. This onl' specifies the name and t'pe of the arra', (ut does not
reserve an' space for the arra'. ;uring the program e+ecution, the arra' must (e allocated. The
allocation will create the space for the arra'. =nl' after the arra' has (een allocated can it (e used.
12
:hapter 13 M %ingle ;imension ,rra's
0or e+ample, to declare an arra',
integer, dimension(:), allocatable :: nums2
reserving the name nums2, (ut not reserving an' space for values.
13.1.3.1 Dynamic 2rray 2llocation
To allocate the space for the arra', the allocate statement must (e used. >efore an arra' can (e allocated, it
must (e declared as allocata(le. The general form of the allocate statement is$
allocate(<array name>, stat=<status variable>)
The status varia(le must (e an integer varia(le and will (e used (' the s'stem to place a status code
indicating the status 3success or failure4 of the operation. .f the status varia(le is set to 0, the allocation
was successful. .f the status varia(le is set to [0, an error occurred and the allocation was not
unsuccessful.
0or e+ample, given the declarations,
integer, dimension(:), allocatable :: nums2
integer :: allst
the following allocate statement allocates space for 1000 num(ers in arra' nums2,
allocate(num2(1000), stat=allst)
The si@e, 1000 in this e+ample, can (e a varia(le, (ut it must (e an integer. The varia(le allst will (e
set to 0 if the allocation is successful and [0 if the allocation failed.
1!. %ccessing %rray ,lements
To access elements in an arra', the arra' name and the an inde+ must (e specified. The inde+ is must
(e an integer or integer e+pression and enclosed in parentheses. The general format is,
array-name(<integer expression>)
0or e+ample, given the declaration,
real, dimension(10) :: times
would declare an arra' with ten elements. To place a value 121.3 in the first arra' element,
times(1) = 121.3
,nd to place 1C.125 in the fifth element,
times(5) = 98.125
The inde+ in these e+amples is a literal. However, the inde+ can (e an integer varia(le or integer
e+pression.
13
:hapter 13 K %ingle ;imension ,rra's
0or e+ample, given the following declarations,
real, dimension(10) :: temps
integer :: i=5, j
would declare an arra' with ten elements. To place a value 1C.E in the fifth arra' element,
temps(i) = 98.6
To access the fifth element, su(tract 3.0 and place the result in the si+th element,
temps(i+1) = temps(i) 3.0
To set all elements of the temps arra' to 0.0, a loop could (e used as follows$
do j = 1, 10
temps(i) = 0.0
end do
,rra' elements can (e accessed as man' times as needed.
1!.! Im"lied #o<Loo"
,n implied do6loop is a special form of a loop that can (e performed on one line. This can (e useful
for accessing elements in an arra'. 0or e+ample, assuming i is declared as an integer, the following
code,
do i = 1, 5
write(*,*) nums(i)
end do
would displa' each element the 5 element arra' to the screen.
The same thing can (e accomplished with an implied do6loop as follows$
write(*,*) (nums(i), i=1,5)
>oth forms of the loop will displa' the same results. .f necessar', a step can (e used. .f the step is
omitted, as in the e+ample, the step is defaulted to 1.
1!.$ Initiali(ing %rrays
,n arra' can (e initiali@ed when it is declared. Each element in the arra' can (e initiali@ed to a single
value or each element to a different value. The following declaration,
real, dimension(10) :: numbers = 1.0
will initiali@e each of the 10 elements in the arra' num(ers to 1.0.
To initiali@e each element to a different value, each value needs to (e specified. 0or e+ample, the
following declaration,
real, dimension(5) :: numbers = (/ 1.0, 2.0, 3.0, 4.0 5.0 /)
will initiali@e each of the 5 elements in the arra' num(ers to 1.0, 2.0, 3.0, <.0, and 5.0 respectivel'.
1<
:hapter 13 M %ingle ;imension ,rra's
The implied do6loop ma' also (e used. 0or e+ample, in the following declaration,
integer, dimension(5) :: numbers = (/ (i, i=1,5) /)
will initiali@e each of the 5 elements in the arra' num(ers to 1, 2, 3, <, and 5 respectivel'.
1!.5 ,xam"le
.n this e+ample we will write a 0ortran program to read a series of num(ers from a file and compute
some statistical information including minimum, ma+imum, sum, average, and standard deviation
C
.
The standard deviation is calculated as follows$
standard de'iation =

i=1
n
a'eragelist i
2
n
,s such, the average must (e calculated (efore the standard deviation.
13.-.1 8n'erstan' the Problem
The program will displa' an initial header and get the file name. %pecificall', we will need to prompt
for the file name, read the file name, and verif' that the file is availa(le (' attempting to open the file.
Then, the program will read the num(ers from the file and store them in an arra'. 0or this pro(lem,
there will (e no more than 5000 num(ers in the file. ,fter the num(ers are in the arra', the minimum,
ma+imum, and sum will (e found. !e+t, the average can (e computed. 0inall', the standard deviation
can (e calculated in steps, the first of which is computing the inner loop. The num(ers should (e
displa'ed, ten per line, followed (' the results.
13.-.2 Create the 2lgorithm
,fter the header is displa'ed, the program should prompt for the file name, read the file name, and
verif' that the file is availa(le (' attempting to open the file. .f the file can not (e opened, the program
will displa' an error message and re6prompt. .f the user does not enter correct information after three
tries, the program should terminate with an appropriate error message. That is, three errors are
accepta(le, (ut if a fourth error is made, the program will terminate.
! declare variables
! integer -> i, ncount, errs, opstat, rdstat
! real -> min, max, sum, stdsum
! real -> array for
! character -> filename(20)
! display initial header
! loop
! prompt for file name
! read file name
! attempt to open file
C 0or more information, refer to$ http$55en.wi)ipedia.org5wi)i5%tandardRdeviation
15
:hapter 13 K %ingle ;imension ,rra's
! if file open successful, exit loop
! display error message
! count error
! if >3 errors, terminate program
! end loop
Then, the program will loop to read the num(ers from the file and store them in an arra'. The program
will chec) for an' read errors 3status varia(le [ 04 and for the end of file 3status varia(le Z 04. .f a
valid num(er is read, it will (e counted and placed in the arra'.
! loop
! read file
! if error on read, terminate program
! if end of file, exit loop
! increment number counter
! place number in array
! end loop
!e+t, another loop will (e used to find the minimum, ma+imum, and sum of the num(ers. To find the
the minimum and ma+imum values, we will assume that the first element in the arra' is the minimum
and ma+imum. Then, the program will chec) each num(er in the arra'. .f the num(er from the arra' is
less than the current minimum value, the current minimum value will (e updated to the new value.
%ame for the ma+imum, if the num(er from the arra' is more than the current ma+imum value, the
current ma+imum value will (e updated to the new value.
! initialize min, max, and sum
! loop
! check for new min
! check for new max
! update sum
! end loop
=nce the sum is availa(le, the average can (e computed. 0inall', a loop will (e used to calculate the
summation for the standard deviation.
! calculate average
! initialize stdsum
! loop
! calculate average array item
! update stdsum
! end loop
=nce the summation is completed, the standard deviation can (e computed and the final results
displa'ed. ,s per the e+ample specifications, the num(ers should (e displa'ed 10 per line. =ne wa' to
handle this is to displa' num(ers on the same line 3with the ad'ance./no/ clause4 and ever' 10
th
line
displa' a new line.
! calculate standard deviation
! loop to display numbers, 10 per line
1E
:hapter 13 M %ingle ;imension ,rra's
! display results
! end program
0or convenience, the steps are written a program comments.
13.-.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program standarddeviation
! declare variables
implicit none
integer :: i, ncount, errs, opstat, rdstat
real :: num, min, max, sum, stdsum
real, dimension(5000) :: numbers
character(20) :: filename
! display initial header
write (*,*) "Standard Deviation Program Example."
! loop
do
! prompt for file name
write (*,'(a)', advance="no") "Enter File Name:"
! read file name
read (*,*) filename
! attempt to open file
open(42, file=filename, status="old", &
action="read", position="rewind", &
iostat=opstat )
! if file open successful, exit loop
if (opstat==0) exit
! display error message
write (*,'(a)') "Error, can not open file."
write (*,'(a)') "Please re-enter."
! count error
errs = errs + 1
! if >3 errors, terminate program
if (errs > 3) then
write (*,'(a)') "Sorry your having problems."
write (*,'(a)') "Program terminated."
stop
end if
! end loop
1B
:hapter 13 K %ingle ;imension ,rra's
end do
! loop
do
! read file
read (42, *, iostat=rdstat) num
! if error on read, terminate program
if (rdstat>0) stop "Error on read."
! if end of file, exit loop
if (rdstat<0) exit
! increment number counter
ncount = ncount + 1
! place number in array
numbers(ncount) = num
! end loop
end do
! initialize min, max, and sum
min = numbers(1)
max = numbers(1)
sum = 0.0
! loop
do i = 1, ncount
! check for new min and new max
if (numbers(i) < min) min = numbers(i)
if (numbers(i) > max) max = numbers(i)
! update sum
sum = sum + numbers(i)
! end loop
end do
! calculate average
average = sum / real(ncount)
! initialize stdsum
stdsum = 0.0
! loop
do i = 1, ncount
! calculate (average array item)^2 and update sum
stdsum = stdsum + (average - numbers(i))**2
! end loop
end do
! calculate standard deviation
1C
:hapter 13 M %ingle ;imension ,rra's
std = sqrt ( stdsum / real(ncount) )
! display results
write (*,'(a)') "-------------------------------"
write (*,'(a)') "Results:"
do i = 1, ncount
write(*,'(2(f8.2,2x))', advance="no") numbers(i)
if (mod(i,10)==0) write(*,*)
end do
write (*,'(a, f8.2)') "Minimum = ", min
write (*,'(a, f8.2)') "Maximum = ", max
write (*,'(a, f8.2)') "Sum = ", sum
write (*,'(a, f8.2)') "Average = ", average
write (*,'(a, f8.2)') "Standard Deviation = ", std
end program standarddeviation
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
13.-.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the program using a file with a set of num(ers
where the correct results are either )nown ahead of time or can (e calculated (' hand in order to verif'
that the results are accurate.
1!.0 %rrays of 'trings
,n arra' ma' also contain characters or strings. The declaration and and access of arra' elements is
the same. However, the string si@e must (e included in the declaration and can not (e easil' changed
once define. 0or e+ample, to declare an arra' to hold 100 titles where each title is a ma+imum of <0
characters,
character(40), dimension(100) :: titles
%etting an element is the same. 0or e+ample, to set the first element of the arra' to the title of this te+t,
titles(1) = Introduction to Programming using Fortran 95
:haracter arra's ma' (e staticall' or d'namicall' declared as noted in the previous sections.
1!.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
13.5.1 Quiz Questions
>elow are some Aui@ Auestions.
11
:hapter 13 K %ingle ;imension ,rra's
14 E+plain wh' an arra' is considered a direct access structure.
24 :an arra's hold integer values 3'es5no4N
34 :an arra's hold real values 3'es5no4N
<4 8rite the declarations for the following$
a4 ,n integer constant, %.WE1, set to 100
(4 ,n arra' with 10 real elements
c4 ,n arra' with %.WE1 integer arguments
d4 ,n arra' with 10 real elements whose su(script values range from 0 to 1
54 iven the declarations and follow code$
integer, dimension(4) :: arr
integer :: k
arr(1) = 10
arr(2) = 15
arr(3) = 20
arr(4) = 25
k = 3
a4 8hat does arr(1) eAualN
(4 8hat does arr(1) + arr(2) eAualN
c4 8hat does arr(1+2) eAualN
d4 8hat does arr(k) eAualN
E4 8hen can an arra' (e allocated 3two options4N
B4 iven the following statements, what values are in arra' after e+ecution.
integer, dimension(5) :: nums
integer :: i=1
do
if ( i == 5 ) exit
if ( mod(i,2) == 0) then
nums(i) = 0
else
nums(i) = i
end if
i = i + 1
end do
C4 8hat is the (nums(i), i=1,5) referred to asN
14 8hat does write(*,*) (nums(i), i=1,5) displa'.
100
:hapter 13 M %ingle ;imension ,rra's
13.5.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the standard deviation program, compile, and e+ecute the program. Test the program
on a series of different input values.
24 8rite a 0ortran program to cu(e read a series of integer num(ers from a file and cu(e each
num(er. The program should also calculate the real average of the original num(ers and the
real average of the cu(ed num(ers. Test the program on a series of different input values.
34 8rite the program to generate a series of real values (etween 1.0 and 100.0 and store the
num(ers in an arra'. Then, the program should compute the norm of a vector 3single dimension
arra'4. The formula for norm is as follows$
norm =

a
1
2
+ a
2
2
+ a
3
2
+ ... + a
n
2
*efer to ,ppendi+ : for more information regarding generating random num(ers. Test the
program on a series of different input values.
<4 8rite a 0ortran program to read a series of num(ers from a file, store the num(ers in an arra',
and then sort the num(ers using the following selection sort algorithm$
for i = len downto 1
big = arr(1)
index = 1
for j = 1 to i
if arr(j) > big
big = arr(j)
index = j
end_if
end_for
arr(index) = arr(i)
arr(i) = big
end_for
#ou will need to convert the a(ove pseudo6code algorithm into 0ortran code. Test the program
on a series of different input values.
101
:hapter 13 K %ingle ;imension ,rra's
102
1$ 4ultidimensional %rrays
, more advanced arra' is a multidimensional arra'. , multidimensional arra' can (e thought of as a
multiple columns in a spreadsheet. The column name, li)e , /, C, etc. are the arra' columns and the
num(er is li)e the row.
0or e+ample, a two dimension arra' might loo) li)e$
inde+ 1 2
,rra' !ame 1 Zvalue[ Zvalue[
2 Zvalue[ Zvalue[
3 . . . . . .
. . . . . .
Zvalue[ Zvalue[
n Zvalue[ Zvalue[
The specific s'nta+ reAuires an inde+ or su(script to specif' which element of the arra' to access. The
inde+ing for a two dimension arra' is$
inde+ 1 2
,rra' !ame 1 arr31,14 arr31,24
2 arr32,14 arr32,24
3 arr33,14 arr33,24
. . . . . .
. . . . . .
n arr3n,14 arr3n,24
>' default, the first element is at inde+U1, the ne+t at inde+U2, and so forth. This default 3where the
first num(er is at inde+ 14 can (e changed if needed.
1$.1 %rray #eclaration
Iultidimensional arra' declaration is ver' similar to single6dimension arra' declaration. ,rra's must (e
declared (efore use. The t'pe of the arra' is defined followed (' the si@e or dimension, which in this case
reAuires a si@e for each dimension. ,s (efore, there are two wa's to declare an arra'P static and d'namic.
103
:hapter 1< K Iultidimensional ,rra's
14.1.1 tatic Declaration
, static declaration means that the si@e or dimension of the arra' must (e defined initiall' 3(efore the
program is compiled4. The si@e definition can not (e altered. The general form of an arra' declaration is,
type, dimension(extent,extent) :: name1, name2, , nameN
where t%pe is the data t'pe 3integer, real, etc.4 of the arra'. The dimension specifies the the si@e, and name1,
name2, b, name! are names of one or more arra's (eing declared.
0or e+ample, to declare a two6dimensional arra' 100 (' 100,
integer, dimension(100,100) :: nums1
will create an arra', nums1, with space for a total of 1000 integer values.
.n this e+ample the e+tent for each dimension is 100 which means that each of the two dimension7s
inde+es will range form 1 to 100. Each or (oth e+tent7s can (e changed (' specif'ing the e+tents as$
(smaller-integer:larger-integer, smaller-integer:larger-integer)
8hen onl' one num(er is specified, the smaller6integer is assumed to (e 1. 8hen (oth num(ers,
smaller and larger inde+, are specified the dimension of the arra' will range (etween the smaller6
integer and the larger6integer. 0or e+ample, a declaration of$
integer, dimension(0:9,0:9) :: ranges
will create an arra', ranges, with (oth inde+es (etween 0 and 1 3inclusive4. "sing inde+ values not
within the specified range will result in an error.
14.1.2 Dynamic Declaration
The same as single dimension, a d'namic declaration means that the dimension of the arra' can (e set when
the program is e+ecuted. =nce set, the dimensions can not (e altered. 8hen using a d'namic declaration,
the arra' t'pe and name must (e defined, which specifies onl' the name and t'pe of the arra', (ut does not
reserve an' space for the arra'. Then, during program e+ecution, the arra' can (e allocated which will
create the space for the arra'. =nl' after the arra' has (een allocated can it (e used.
0or e+ample, to declare an arra',
integer, dimension(:,:), allocatable :: nums2
reserving the name nums2, (ut not reserving an' space for values.
14.1.3 Dynamic 2rray 2llocation
To allocate the space for the arra', the allocate statement must (e used. >efore an arra' can (e allocated, it
must (e declared as allocata(le.
The general form of the allocate statement is$
allocate(<array name>, <dimension>, stat=<status variable>)
The status varia(le must (e an integer varia(le and will (e used (' the s'stem to place a status code
indicating the status 3success or failure4 of the operation. ,s (efore, if the status varia(le is set to 0, the
10<
:hapter 1< M Iultidimensional ,rra's
allocation was successful. .f the status varia(le is set to [0, an error occurred and the allocation was
not unsuccessful.
0or e+ample, given the declarations,
integer, dimension(:,:), allocatable :: nums2
integer :: allstat
the following allocate statement allocates space for 1000 num(ers in arra' nums2,
allocate(nums2(100,100), stat=allstat)
The si@e, 100 (' 100 in this e+ample, can (e a parameter or varia(le, (ut it must (e an integer. The
varia(le allst will (e set to 0 if the allocation is successful and [0 if the allocation failed.
1$. %ccessing %rray ,lements
To access elements in an arra', the arra' name and the an inde+ must (e specified. The inde+ must include
an integer or integer e+pression for each dimension enclosed in parentheses. The general format is,
array-name(<integer expression>, <integer expression>)
0or e+ample, given the declaration,
real, dimension(10,5) :: table1
would declare an arra', table1, with a total of 50 elements. To place a value 121.3 in the first row and first
column,
table1(1,1) = 121.3
,nd to place 1C.125 in the tenth row and fifth column,
table1(10,5) = 98.125
The inde+ in these e+amples is a literal. However, the inde+ can (e an integer varia(le or integer
e+pression. 0or e+ample, given the following declarations,
real, dimension(10,10) :: tmptable
integer :: i=2, j=3
would declare an arra', tmptable, with ten elements.
To place a value 1C.E in the second row, fourth column,
tmptable(i,j+1) = 98.6
To access the same element, su(tract 3.0 and place the result (ac) into the same location,
tmptable(i,j+1) = tmptable(i,j+1) 3.0
105
:hapter 1< K Iultidimensional ,rra's
To set all elements of the tmptable arra' to 0.0, a nest loop could (e used as follows$
do i = 1, 10
do j = 1, 10
tmptable(i,j) = 0.0
end do
end do
.n addition, the entire arra' can (e set to 0 in the following statement,
tmptable = 0.0
,rra' elements can (e accessed as man' times as needed.
1$.! ,xam"le
.n this e+ample we will write a 0ortran program that will reAuest a count, generate count 3x,#4 random
points, and perform a Ionte :arlo ; estimation (ased on those points. ,ll x and # values are (etween
0 and 1. The main routine will get the count and the use a su(routine to generate the random 3x,#4
points and a function, to perform the Ionte :arlo ; estimation. 0or this e+ample, the count should (e
(etween 100 and 1,000,000.
14.3.1 8n'erstan' the Problem
>ased on the pro(lem definition, we will use a main routine that will get and chec) the count value. .f
the count is not (etween 100 and 1,000,000, the routine will re6prompt until the correct input is
provided. =nce a valid count value is o(tained,
then the main will allocate the arra' and call the
two su(routines. The first su(routine will
generate the random 3x,#4 points and store them
in an arra'. The second su(routine will perform
the Ionte :arlo ; estimation.
Ionte :arlo methods are a class of
computational algorithms that rel' on repeated
random sampling to compute their results.
%uppose a sAuare is centered on the origin of a
:artesian plane, and the sAuare has sides of
length 2. .f we inscri(e a circle in the sAuare, it
will have a diameter of length 2 and a radius of
length 1. .f we plot points within the upper right Auadrant, the ratio (etween the points that land within
the inscri(ed circle and the total points will (e an estimation of ;.

est 0 = <

samples inside circle
total samples

,s more samples are ta)en, the estimated value of ; should approach the actual value of ;. The
/'thagorean theorem can (e used to determine the distance of the point from the origin. .f this distance
10E
:hapter 1< M Iultidimensional ,rra's
is less than the radius of the circle, then the point must (e in the circle. Thus, if the sAuare root of
3x
2
O#
2
4 Z 1.0, the random point is within the circle.
0inall', the figure we are discussing, a sAuare centered on the origin with an inscri(ed circle is
s'mmetric with respect to the Auadrants of its :artesian plane. This wor)s well with the default
random num(er generations of values (etween 0 and 1.
14.3.2 Create the 2lgorithm
The main routine will displa' an initial header, get and chec) the count value, and allocate the arra'.
The program will need to ensure that the arra' is correctl' allocated (efore proceeding. Then program
can generate the 3x,#4 points. >ased on the pro(lem definition, each point should (e (etween 0.0 and
1.0 which is provided (' default (' the 0ortran random num(er generator. !e+t, the program can
perform the Ionte :arlo pi estimation. This will reAuire the alread' populated 3x,#4 points arra' and
the count of points. Each point will (e e+amined to determine the num(er of points that lie within the
inscri(ed circle. The /'thagorean theorem allows us to determine the distance of the point from the
origin 30.0,0.04. Thus, for each point, we will calculate the
x2%2 and if the distance is less than
the circle radius of 1.0, it will (e counted as inside the circle.
Then, the estimated value of ; can (e calculated (ased on the formula$
est = 4
(
$amp&e$ in$ide circ&e
tota& $amp&e$
)
8hen completed, the program will displa' the final results. The (asic algorithm is as follows$
! declare variables
! display initial header
! prompt for and obtain count value
! loop
! prompt for count value
! read count value
! if count is correct, exit loop
! display error message
! end loop
! allocate two dimension array
! generate points
! loop count times
! generate x and y values
! place (x,y) values in array at appropriate index
! end loop
! set count of samples inside circle = 0
! loop count times
! if [ sqrt (x(i)
2
+y(i)
2
) < 1.0 ]
! increment count of samples inside circle
! end loop
! display results
0or convenience, the steps are written a program comments.
10B
:hapter 1< K Iultidimensional ,rra's
14.3.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program piestimation
! declare variables
implicit none
integer :: count, alstat, i, incount
real :: x, y, pi_est, pt
real, allocatable, dimension(:,:) :: points
! display initial header
write (*,'(/a/)') "Program Example PI estimation."
! prompt for and obtain count value
do
! prompt for count value
write (*,'(a)', advance="no") &
"Enter Count (100 1,000,000): "
! read count value
read (*,*) count
! if count is correct, exit loop
if ( count >= 100 and count <= 1000000 ) exit
! display error message
write (*,'(a,a,/a)') "Error, count must be ", &
"between 100 and 1,000,000.", &
"Please re-enter."
end do
! allocate two dimension array
allocate (points(count,2), stat=alstat)
if (alstat <> 0 ) then
write (*,'(a,/a)') "Error, unable to allocate" &
" memory.", "Program terminated."
stop
end if
! generate_points
call random_seed()
! loop count times
do i = 1, cnt
! generate x and y values
call random_number(x)
call random_number(y)
! place (x,y) values in array
pts(i,1) = x
pts(i,2) = y
10C
:hapter 1< M Iultidimensional ,rra's
end do
! perform monte carlo estimation
! set count of samples inside circle = 0
incount = 0
! loop count times
do i = 1, cnt
! if [ sqrt (x(i)
2
+y(i)
2
) < 1.0 ]
! increment count of samples inside circle
pt = pts(i,1)**2 + pts(i,2)**2
if (sqrt(pt) < 1.0) incount = incount + 1
end do
pi_est = 4.0 * real(incount) / real(cnt)
! display results
write (*,'(a, f8.2)') "Count of points: ", count
write (*,'(a, f8.2)') "Estimated PI value: ", pi_est
end program piestimation
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
14.3.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the program using a series of different count
values and ensure that the ; estimate is reasona(le and improves with higher count values.
1$.$ ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
14.4.1 Quiz Questions
>elow are some Aui@ Auestions.
14 :an multidimensional arra's hold (oth integer and real values 3'es5no4N
24 8hat is the order of the inde+es$
1. 3row, column4
2. 3column, row4
3. 3row, row4
<. 3column, column4
5. user6selecta(le
101
:hapter 1< K Iultidimensional ,rra's
34 iven the following code$
real, dimension(5,3) :: mdarr
integer :: i, j
do i = 1, 5
do j = 1, 3
mdarr(i,j) = real(i+j)
end do
end do
a4 How man' values, total, can (e stored in the mdarr arra'N
(4 %how the contents of ever' cell in the mdarr. 35 pts4
c4 8hat does mdarr(2,1) containN
d4 8hat does mdarr(1,3) containN
e4 8hat does mdarr(4,3) containN
<4 How can an unsuccessful multidimensional d'namic allocation (e detectedN
14.4.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the ; estimation program compile, and e+ecute the program. Test the program on a
series of different point count values. ;emonstrate that larger point values provide a (etter
estimation.
24 "pdate the ; estimation program to ensure that a valid count values is o(tained within three
tries. .f there are more than three errors, the program should displa' an error message and
terminate.
34 "pdate the ; estimation program to displa' the estimated ; value 10 times. .n order to perform
this, the count value can (e divided (' 10 and the current estimated ; value displa'ed.
<4 8rite a program to staticall' declare a 100+100 two dimensional arra' of real values. The
program should populate the arra' with random num(ers (etween 0 3inclusive4 and 1
3e+clusive4. *efer to ,ppendi+ : for information regarding generating random num(ers. The
program should scan the arra' to find and displa' the ma+imum value and the location of that
value 3ie., the row and column where the value was found4.
54 "pdate the find ma+imum program 3from the previous Auestion4 to declare the arra'
d'namicall' and allow the user to enter a the row and column dimension7s and ensure that each
is (etween 10 and 1000. =nce entered, the program should allocate the arra' and find and
displa' the ma+imum and minimum values and their locations 3row and column4.
110
:hapter 1< M Iultidimensional ,rra's
E4 8rite a 0ortran program to construct an odd6order Iagic %Auare
1
. The algorithm for
constructing an !+! odd ordered Iagic %Auare is as follows$
0irst, place a 1 in the middle of the top row.
,fter placing an integer, 0, move up one row and one column to the right to place the
ne+t integer, 011, unless the following occurs$
.f a move ta)es 'ou a(ove the top row in the (
th
column, move to the (ottom of the (
th
column and place the integer there.
.f a move ta)es 'ou outside to the right of the sAuare in the i
th
row, place the integer
in the i
th
row at the left side.
.f a move ta)es 'ou to an alread' filled sAuare or if 'ou move out of the sAuare at
the upper right hand corner, place 011 immediatel' (elow 0.
Test the program and compare the results to the 8i)ipedia e+ample.
1 0or more information, refer to$ http$55en.wi)ipedia.org5wi)i5IagicRsAuare
111
:hapter 1< K Iultidimensional ,rra's
112
15 'ub"rograms
"ntil now, all of the programs have essentiall' (een a single, fairl' small programs. However, as we
scale up into larger programs, this methodolog' will (ecome more difficult. 8hen developing larger
programs, it (ecomes necessar' to (rea) the larger program up into multiple, smaller more managea(le
pieces. Then, during program development, it is possi(le to focus on each su(section or piece
individuall' and then com(ine the results into a final complete program. ,nd, for ver' large proFects,
multiple people ma' wor) on different parts of the program simultaneousl'.
%ome of the )e' advantages of developing a program using functions and5or su(routines include$
%tructured development of programs
*euse of su(programs
.solation of su(programs
0ortran su(programs are the mechanism to (rea) a large program into multiple smaller parts. This
allows for a more comprehensive program design.
15.1 'ub"rogram Ty"es
There are two t'pes of 0ortran su(programs$ (unctions and subroutines, each of which is e+plained in
the following sections.
15. Program Layout
The functions and su(routines can (e defined as either internal or e+ternal. .nternal functions and
su(routines are (e defined within the program statement 3i.e., (efore the -end program Zname[2
statement4.
The (asic la'out for (oth internal and e+ternal su(programs is as follows$
program <name>
<declarations>
<program statements>
contains
<internal functions or subroutines>
end program <name>
<external functions or subroutines>
8here a com(ination of (oth or either internal or e+ternal routines is allowed.
113
:hapter 15 K %u(programs
1-.2.1 ,nternal Routines
.nternal routines reAuire the )e'word -contains2 to separate the from the program code. /rimaril',
internal routines will (e used in this te+t for simplicit'. There is no limit to the num(er of internal
routines. However, if too man' routines are included the file will (ecome large and large files can (e
difficult to wor) with.
1-.2.2 "#ternal Routines
E+ternal functions are defined outside the program statement 3i.e., after the -end program Zname[2
statement4 or in another file. 0or larger programs e+ternal routines would (e used e+tensivel'.
However, additional set6up statements, including an external declaration and an inter(ace bloc-, are
reAuired. The definition and use of e+ternal routines is not addressed in this chapter.
15.! %rguments
8hen writing and using 0ortran su(programs, it is t'picall' necessar' to provide information to and5or
o(tain results from the functions or su(routines. This information, in the form of varia(les, is referred
to as an argument or arguments. The argument or arguments in the calling routine is referred to as
actual arguments and the argument or arguments in the function or su(routine are referred to as (ormal
arguments. The formal arguments ta)e on the values that are passed from the calling routine.
The onl' wa' to transfer values in to or out of a function or su(routine is through the arguments. ,ll
other varia(les are independent and isolated.
1-.3.1 2rgument ,ntent
%u(programs often return values (' altering or update the some of the arguments. 8hen passing a
varia(le, the information 3value or values4 can (e passed into the function or su(routine. This is
referred to as -intent3in42. .f the varia(le is to (e set (' the su(routine, that is referred to as
-intent3out42. .f the varia(le contains a value or values 3i.e., an arra'4 that are to (e passed into the
su(routine and altered in some wa' (' the su(routine and returned (ac) to the calling routine, that is
referred to as -intent3inout42.
15.$ 3ariable 'co"e
The varia(le scope refers to where a given varia(le can (e accessed. %cope rules tell us if an entit'
3i.e., varia(le, parameter, and5or function4 is visi(le or accessi(le at certain places. /laces where an
entit' can (e accessed or visi(le is referred as the scope of that entit'. The varia(les defined in a
su(program is generall' not visi(le to the calling routine. Thus a varia(le x in the calling routine is
different than a varia(le x in the su(program.
15.5 6sing Functions and 'ubroutines
>efore a function or su(routine can (e used, it must (e defined or written. =nce defined, the
su(routine or function can (e used or called. , function is called (' using its name as we have done
with the intrinsic functions. 8hen a program uses a su(routine it is called with a call statement.
11<
:hapter 15 M %u(programs
1-.-.1 2rgument Passing
8hen using functions and5or su(routines, information 3values, varia(les, etc.4 are t'picall' passed to or
from the routines. ,rgument association is a wa' of passing values from actual arguments to formal
arguments. .f an actual argument is an e+pression, it is evaluated and passed to the corresponding
formal argument. .f an actual argument is a varia(le or constant, its value is passed to the
corresponding formal argument. There must (e a one6to6one correspondence (etween the actual
argument 3calling routine4 and the formal argument 3su(routine5function4.
The arguments in the call are matched up to the arguments in the su(routine (' position. Each of the
arguments is matched (' position. The names of the varia(les do not need to match, however the data
t'pes must match.
Ca&&ing 6outine
...
call example (x, y, z)
...
Su0routine
...
subroutine example (a, b, c)
...
=ther varia(les in either the calling routine or the su(routine are isolated from each other. ,s such, the
same varia(le name can (e re6used in (oth the calling routine and the su(routine 3and refer to different
values4.
15.0 Functions
, function is a special t'pe of 0ortran su(program that is e+pected to return a single result or answer.
, function will t'picall' accept some )ind of input information and (ased on that information, return a
result. The two t'pes of 0ortran functions are descri(ed in the following sections.
1-.&.1 ,ntrinsic %unctions
, descri(ed previousl', an intrinsic (unction is a (uilt6in function that is alread' availa(le. %ome of the
intrinsic functions alread' descri(ed include sin)*, cos)*, tan)*, real)*, int)*, and nint)*. , more
comprehensive list is contained in ,ppendi+ ;.
1-.&.2 8ser1De<ine' %unctions
, user6defined function are functions that a written (' the user for specific or speciali@ed reAuirements.
115
:hapter 15 K %u(programs
The general form of a user6defined function is a follows$
<type> function <name> ( <arguments> )
<declarations>
<body of function>
<name> = expression
return
end function <name>
The Zt'pe[ is one of the 0ortran data t'pesP real, integer, logical, character, or comple+. .t is possi(le
to place the t'pe declaration on a separate line from the functions statement.
The information, in the form of arguments, is passed from the calling routine to the function. Each of
the passed arguments must (e declared and the declaration must include the t'pe and the intent. The
arguments in the calling routine and the function must match and are matched up (' position.
,n e+ample function to convert a 0ahrenheit temperature to :elsius temperature would (e as follows$
real function fahr_to_celsius(ftemp)
real, intent(in) :: ftemp
fahr_to_celsius = (ftemp 32.0) / 1.8
return
end function fahr_to_celsius
end program quiz
8hich, given a 0ahrenheit temperature, will return the :elsius temperature. The single input argument,
(temp, is declared to (e a real value and -intent3in42, which means that the value is e+pected to (e
coming into the function and can not (e changed. The final value is returned to the calling routine ('
assigning a value to the function name, (ahr1to1celsius, in this e+ample.
1-.&.2.1 i'e "<<ects
, side$e((ect is when a function changes one or more of its input arguments. %ince the arguments can
(e declared as -intent3out42 or -intent3inout42, the function could change the arguments. .n general,
this is consider poor practice and should (e avoided. !one of the e+amples in this te+t will include or
utili@e side6effects.
15.5 'ubroutines
, su(routine is a 0ortran su(program that can accept some )ind of input information and (ased on that
information, return a result or series of results.
11E
:hapter 15 M %u(programs
The general form of a su(routine is a follows$
subroutine <name> ( <arguments> )
<declarations>
<body of subroutine>
return
end function <name>
The information, in the form of arguments, is passed from the calling routine to the function. Each of
the passed arguments must (e declared and the declaration must include the t'pe and the intent. The
arguments in the calling routine and the su(routine must match and are matched up (' position.
0or e+ample, given the following simple program to find the sum and average of three num(ers.
program subexample
implicit none
real :: x1=4.0, y1=5.0, z1=6.0, sum1, ave1
real :: x2=4.0, y2=5.0, z2=6.0, sum2, ave2
call smave(x1, y1, z1, sum1, ave1)
write(*,'(a,f5.1,3x,a,f5.1)') "Sum=", sum1, "Average=", ave1
call smave(x2, y2, z2, sum2, ave2)
write(*,'(a,f5.1,3x,a,f5.1)') "Sum=", sum2, "Average=", ave2
contains
subroutine smave (a, b, c, sm, av)
real, intent(in) :: a, b, c
real, intent(out) :: sm, av
sm = a + b + c
av = sm / 3.0
return
end function smave
end program subexample
The arguments in the first call 3x1, %1, 21, sum1, and a'e14 are matched up to the arguments in the
su(routine 3a, b, c, sm, and a'4 (' position. That is, the x1 from the call is matched with the a in the
su(routine. The arguments in the second call 3x2, %2, 22, sum2, and a'e24 are again matched up to the
arguments in the su(routine 3a, b, c, sm, and a'4 (' position. 8hile the names of the varia(les do not
need to match, the data t'pes must match. Varia(les declared in a function or su(routine are not the
same as varia(les in the calling routine. This is true, even if the' are the same name\
11B
:hapter 15 K %u(programs
15.8 ,xam"le
.n this e+ample we will write a 0ortran program to simulate the dice game of Twent'6%i+
10
which is
single pla'er (etting game with 10 dice. The main program will determine how man' games to pla'. ,
su(routine will (e used to pla' the Twent'6%i+ game. The su(routine will (e called as man' times as
reAuested. The main will trac) the count of games won and lost and displa' the win5loss record and the
win percentage.
The su(routine, twent#2six34, will pla' the game dice game Twent'6%i+. To pla' the game, the pla'er
rolls the dice 31 to E4 and this initial roll is used as the -point2 num(er. Then the pla'er throws the ten
dice 13 times. The score is the num(er of times that the point num(er is thrown. , random num(er
(etween 1 and E will (e used for each dice roll.
The routine will determine the pa'out (ased on the point count using the following ta(le$
Point Count Payout
+, or 'ess +,
+- %
./ 0
.1 %
.2 /
.$ 2
-, +,
Other ,
The su(routine should displa' the dice 3all 10 dice for each of 13 rolls4, point count, game result,
pa'out. 0or e+ample, if the point was E, the su(routine might displa' the following$
Point: 6
Roll: 1 Dice: 4 6 5 3 3 1 1 3 3 2
Roll: 2 Dice: 1 6 3 3 4 1 4 4 2 6
Roll: 3 Dice: 3 2 6 4 5 3 2 1 5 4
Roll: 4 Dice: 5 6 4 1 4 6 6 2 4 4
Roll: 5 Dice: 4 6 6 4 5 3 6 1 5 5
Roll: 6 Dice: 3 1 4 5 6 5 3 3 3 4
Roll: 7 Dice: 6 6 5 6 1 5 5 6 5 5
Roll: 8 Dice: 4 1 3 4 1 4 4 6 2 5
Roll: 9 Dice: 4 4 2 1 1 4 3 1 5 4
Roll: 10 Dice: 5 6 1 2 4 1 1 2 1 1
Roll: 11 Dice: 2 3 2 4 1 3 3 6 5 1
Roll: 12 Dice: 1 1 6 5 4 5 1 6 6 5
Roll: 13 Dice: 6 4 4 5 3 3 5 3 3 5
Point Count: 22
Game Result: LOSS Payout = 0
0or this e+ample, the main will trac) the games won and lost.
10 0or more information, see$ http$55homepage.ntlworld.com5dice6pla'5ames5Twent'%i+.htm
11C
:hapter 15 M %u(programs
1-.6.1 8n'erstan' the Problem
The program will displa' an initial header and get the num(er of games to pla'. %pecificall', we will
need to prompt for the count of games and and verif' that the count is (etween 2 and 1,000,000
3ar(itraril' chosen4. Then, the program will call the twent#2six34 su(routine count times. ,fter each
game, the main will update the count of games won. The main will also trac) the pa'out and (an)
value status, which is initiali@ed to 100 3chosen ar(itraril'4 and updated after each game is pla'ed.
,n e+ample main is provided as follows$
program dicegame
!-----------------------------------------------------------
! Fortran program to simulate a dice game of Twenty-Six
! The main program:
! displays appropriate headers
! obtains and checks number of games to play
! loops to play 'count' number of games times
implicit none
integer, parameter :: initial_bank=100
integer :: num_games, games_won=0, games_lost=0
integer :: i, payout, bank
integer, dimension(13,10) :: dice
real :: win_pct
write (*, '(/a/a/)') &
"--------------------------------", &
"Dice Game ""Twenty-Six"" Simulator."
do
write (*, '(2x, a )', advance = "no") &
"Enter number games to simulate: "
read (*,*) num_games
if (num_games >= 1 .and. num_games <= 1000000) exit
write (*, '(2x, a)') "Error, number of ", &
"games must be between 1 and 1000000."
write (*, '(2x, a)') "Please re-enter."
end do
bank = initial_bank
call random_seed()
do i = 1, num_games
bank = bank - 1
call twenty_six (payout)
if (payout > 0) then
games_won = games_won + 1
else
games_lost = games_lost + 1
end if
111
:hapter 15 K %u(programs
bank = bank + payout
end do
win_pct = ( real(games_won) / real(num_games) ) * 100.00
write (*,'(/a,/a/,3(2x,a,i9/),2(2x,a,i8/),2x,a,f4.1,a)') &
"------------------------------------------------" &
"Games Statistics:", &
"Game Count: ", num_games, &
"Games Won: ", games_won, &
"Games Lost: ", games_lost, &
"Initial Bank: ", initial_bank, &
"Final Bank: ", bank, &
"Win Percentage: ", win_pct, "%"
contains
! *********************************************************
! subroutine(s) goes here...
! *********************************************************
end program dicegame
*efer to ,ppendi+ : for additional information regarding the random num(er generation and
initiali@ation of the (uilt6in random num(er generator.
1-.6.2 Create the 2lgorithm
%ince the main is provided, the algorithm will focus on the twent'6si+ game. %ince the (uilt6in random
num(er generator provides random num(ers (etween 0.0 and 1.0, the' will need to (e scaled and
converted to an integer (etween 1 and E 3for a dice4. The initial point value must first (e esta(lished
followed (' a loop to throw the ten dice 13 times in accordance with the game rules. The results will
(e stored in a two6dimensional arra'. 8hile not strictl' reAuired, it does provide an additional e+ample
of how to use a two6dimensional arra'. 0inall', the pa'out will (e determined (ased on the game rules.
! Randomly select a number from 1 to 6 as the "point" number
! Throw ten dice 13 times
! results go into dice(13,10) array
! Score is the number of times that the point number
! is thrown
! determine payout
0or convenience, the steps are written a program comments.
1-.6.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
! *********************************************************
! Subroutine to simulate twenty-six game.
120
:hapter 15 M %u(programs
! Randomly select a number from 1 to 6 as the point number
! Throw ten dice 13 times
! results go into dice(13,10) array
! Score is the number of times that the point number is thrown
subroutine twenty_six (payout)
implicit none
integer, dimension(13,10) :: dice
integer, intent(out) :: payout
integer :: point, pnt_cnt
real :: x
integer :: i, j
! determine point
call random_number(x)
point = int(x*6.0) + 1
! roll dice
pnt_cnt = 0
do i = 1, 13
do j = 1, 10
call random_number(x)
dice(i,j) = int(x*6.0) + 1
if (dice(i,j) == point) pnt_cnt = pnt_cnt + 1
end do
! determine payout
select case (pnt_cnt)
case (6, 10)
payout = 10
case (13,27)
payout = 5
case (26)
payout = 4
case (28)
payout = 6
case (29)
payout = 8
case (30:36)
payout = 10
case default
payout = 0
end select
end do
write (*,'(/,5x,a,/,5x,a,i2,/,5x,a,i2)') &
"--------------------------------------", &
"Point: ", point
do i = 1, 13
write (*,'(8x, a, i2, 2x, a, 10(2x, i1),/)', &
121
:hapter 15 K %u(programs
advance="no") "Roll: ", i, "Dice: ", &
(dice(i,j), j=1,10)
end do
write (*,'(/,5x,a,i2)') "Point Count: ", pnt_cnt
if (payout > 0) then
write (*,'(5x,a,i2)') &
"Game Result: WIN Payout = ", payout
else
write (*,'(5x,a,i2)') &
"Game Result: LOSS Payout = ", payout
end if
write (*,'(5x,a,i6)') "Bank:", bank
return
end subroutine twenty_six
The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.
1-.6.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the program using a file with a set of num(ers
where the correct results are either )nown ahead of time or can (e calculated (' hand in order to verif'
that the results are accurate.
15.9 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
1-.:.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat are the two t'pes of 0ortran su(programsN
24 How man' values does a user6defined function t'picall' returnN
1-.:.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the dice game program e+ample, compile, and e+ecute the program. Test the program
(' pla'ing it for a series of rounds. Ensure the scoring is correct.
122
:hapter 15 M %u(programs
24 8rite a main program and an integer 0ortran function, g!eries34, to compute the following
geometric series$
g =

n=,
n1
x
n
= 1+x+x
2
+x
3
+ +x
( n1)
The arguments for the call, in order, are as followsP n 3integer value4. The function should
return an integer result. The main should call the function with several different values.
34 8rite a main program and a real function, harmonic5ean34, to compute the harmonic mean of
a series of real num(ers. The real num(ers are pass to the function in an arra' along with the
count.
harmonic mean =
+

1
x
1

1
x
2
...
1
x
+

The arguments for the call, in order, are as followsP arra' of num(ers 3count real values4, count
3integer4. The function should return an real result. The main should call the function with
several different values.
<4 8rite a main program and a su(routine, Circle!tats34, that, given an arra' containing a series of
circle diameter7s 3real values4, will compute the area of each circle in a series of circles and
store them into a different arra' 3real values4. The su(routine should also compute the real
average of the circle areas. The arguments for the call, in order, are as followsP circle diameter7s
arra' 3count real values4, circle areas arra' 3count real values4, count 3integer4, areas average
3real4. The main program should declare the arra' and initiali@e the arra' with a series of values
for circle areas. The program results should (e verified with a calculator.
54 8rite a main program and a su(routine, 6eadCoord34, to read an 3x,#,z4 coordinate from the
user. The su(routine must prompt for and read 3x,#z4 and ensure that the x, #, and z values are
(etween 0 and 100 3inclusive4. The values ma' (e prompted for and read together, (ut prompt
should leave the cursor on the same line. The su(routine should re6prompt for all three if the
input data is not correct. .f the user provides valid data, the 3x,#,z4 values should (e returned
with a logical for valid data set to true. .f the user does not provide valid data entr' after three
tries, the su(routine should displa' an error message and a set the logical for valid data to (alse.
The arguments for the call, in order, are as followsP x value 3integer4, # value 3integer4, z value
3integer4, and valid data flag 3logical value4. The main program should call the su(routine three
times and displa' the results for each call.
123
:hapter 15 K %u(programs
E4 8rite a main program and a su(routine, !tats34, that, given an arra' containing a series of
num(ers 3real values4, will find and displa' the following real valuesP minimum, median,
ma+imum, sum, and average. The displa' must use a formatted write34. The real values will
not e+ceed 100.0 and should displa' three digits decimal values 3i.e., nnn.xxx4. The arguments
for the call, in order, are as followsP arra' of num(ers 3count real values4, count 3integer4. The
main program should populate the arra' with random num(ers and call the su(routine.
12<
10 #eri)ed #ata Ty"es
, derived data t'pe is a user6defined com(ination of the intrinsic data t'pes. The derived data t'pes
are a convenient wa' to com(ine or group varia(les a(out a particular item.
0or e+ample, a 7student7 might include a name, identification num(er, final score, and grade. Each of
these pieces of information can (e represented with individual varia(les 3as outlined in previous
section4 as follows$
character(50) :: name
integer :: id
real :: score
character(2) :: grade
However, for multiple students, multiple sets of varia(les would (e reAuired. This can (ecome
cum(ersome and confusing.
>' using a derived data t'pe, these separate pieces of information can (e more easil' grouped together.
The details on defining, declaring and using derived data t'pes are provided in the following sections.
10.1 #efinition
>efore a derived data t'pe can (e used, it must (e defined. The definition will esta(lish the pieces of
information will (e grouped together. Each piece of information included in the definition is referred
to as a component.
type type_name
<component definitions>
end type type_name
0or e+ample, to declare the student t'pe descri(ed previousl', the following declaration would (e
appropriate$
type student
character(50) :: name
integer :: id
real :: score
character(1) :: grade
end type student
The indentation is not reAuired, (ut does ma)e the definition easier to read. Each of the fields 3name,
id, score, grade4 are called components. These components together ma)e up the information for a
7student7.
The t'pe definition is reAuired onl' once at the (eginning of the program. =nce defined, the t'pe
definition can not (e changed. Iore specificall', additional components can not (e added unless the
definition is updated and program is recompiled.
125
:hapter 1E K ;erived ;ata T'pes
This definition will esta(lish a template as follows$
student name
id
score
grade
=nce defined, the template can (e used to declare varia(les. Each varia(le declared with this definition
will (e created (ased on the definition which includes the these four components.
10. #eclaration
=nce a derived data t'pe is defined, varia(les using that definition can (e declared. The general format
for a declaration is as follows$
type (<type_name>) :: <variable_name(s)>
0or e+ample, to declare two students, the following declaration could (e used$
type (student) :: student1, student2
This declaration will declare two varia(les, student1 and student2, each with the set of components
defined in the t'pe definition. The definition can (e thought of as the coo)ie cutter and the declaration
is the coo)ie. =nl' after a varia(le has (een declared, can values (e set for that varia(le.
10.! %ccessing Com"onents
=nce some varia(les using the derived data t'pe have (een declared, the individual components can (e
accessed. 0irst the varia(le name is specified, followed (' a -c2 3percent sign4, and then the
component name. The general format is$
<variable_name>%<component_name>
0or e+ample, to set all components for the student student1, the following
student1%name = "Joesph"
student1%id = 1234
student1%score = 99.99
student1%grade = "A"
Each component for student1 is set individuall'. !ot ever' component must (e set. =f course, as with
other varia(les, an component that has not (een set can not (e used.
12E
:hapter 1E M ;erived ;ata T'pes
This previous declaration and these assignments will esta(lish a varia(le as follows$
student name
Joesph
id
1234
score
99.99
grade
A
.t is possi(le to assign all components to another varia(le of the same derived data t'pe. 0or e+ample,
to set student2 to the same as student1, an assignment is used as follows$
student2 = student1
This will cop' all components from the varia(le student1 into the varia(le student2 3since (oth
student1 and student2 are of the same derived data t'pe4.
10.$ ,xam"le &ne
.n this e+ample, we will write a simple program to read two times from the user, time one and time
two, and calculate the sum of the two times. 0or this e+ample, the time will consist of hour, minutes,
seconds in 2<6hour format. 0or this e+ercise, the hours ma' e+ceed 23 when the times are summed.
The program should declare the appropriate varia(les using a derived data t'pe, use a su(routine to
read a time 3which should (e called twice4, and another su(routine to calculate the sum of the times.
The su(routine to read the times must perform appropriate error chec)ing. The main should displa'
(oth the times and the final time sum.
1&.4.1 8n'erstan' the Problem
The main is e+pected to define the appropriate derived data t'pe for time, declare some varia(les of
that t'pe and call the su(routines. The first su(routine will read a time from the user which will consist
of hour, minutes, and seconds in 2<6hour format. This su(routine will (e called twice. The second
su(routine will add the times together and provide a result.
The first su(routine to read a time from the user is e+pected to perform error chec)ing on the data
entered (' the user. %pecificall', this reAuires that hours range from 0 to 23, minutes range from 0 to
51, and seconds range from 0 to 51. Values outside these ranges, E0 seconds for e+ample, are not valid.
0or this simple e+ample, we will re6prompt for incorrect data entr' 3until correct data is provided4.
The second su(routine will add the two times and must ensure that the correct ranges for seconds and
minutes are maintained. 8hen adding the two times, it is possi(le to add the seconds, minutes, and
hours. However, if the sum of the two seconds values e+ceeds E0, the seconds must (e adFusted and
the minutes must (e updated accordingl' 3add one e+tra minute4. This applies to the minutes as well.
However, when added in this e+ercise, the final time sum hours ma' e+ceed 23 hours.
0or e+ample, given time one as 1< hours, <B minutes and 22 seconds 3i.e., 1<$<B$224 and time two as 1C
hours, 22 minutes, and 50 seconds, 3i.e., 1C$22$504, the total time would (e 33 hours, 10 minutes and 12
seconds 3i.e., 33$10$124.
12B
:hapter 1E K ;erived ;ata T'pes
1&.4.2 Create the 2lgorithm
0or this e+ample there are three partsP the main, the read time su(routine, and the time summation
su(routine. The (asic steps for the main include$
! define derived data type for time
! must include hours, minutes, seconds
! declare variables, including time1, time2, and timesum
! display initial header
! call subroutine to read time1
! call subroutine to read time2
! call subroutine to add times
! display results
The (asic steps for the read time su(routine include$
! subroutine header and appropriate declarations
! loop
! prompt for time
! read time (hours, minutes, seconds)
! check time entered
! if [ hours(0-23), minutes(0-59), seconds (0-59) ] exit
! display error message
! end loop
The (asic steps for the time summation su(routine include$
! subroutine header and appropriate declarations
! add the seconds
! add the minutes
! add the hours
! if seconds > 59, then
! subtract 60 from seconds
! add 1 to minutes
! if minutes > 59, then
! subtract 60 from minutes
! add 1 to hours
0or convenience, the steps are written a program comments.
1&.4.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program timeSummation
! define derived data type for time (hours, minutes, seconds)
implicit none
type time
integer :: hours, minutes, seconds
end type
12C
:hapter 1E M ;erived ;ata T'pes
! declare variables
! includes time1, time2, and timesum
type(time) :: time1, time2, timesum
! display initial header
write (*,'(/,a,/)') "Time Summation Example Program."
! call subroutine to read each time
call readtime(time1)
call readtime(time2)
! call subroutine to add times
call addtimes(time1, time2, timesum)
! display results
write (*,'(/,a,i2.2,a1,i2.2,a1,i2.2)') "Time One: ", &
time1%hours, ":", time1%minutes, ":", time1%seconds
write (*,'(a,i2.2,a1,i2.2,a1,i2.2)') "Time Two: ", &
time2%hours, ":", time2%minutes, ":", time2%seconds
write (*,'(a,i2.2,a1,i2.2,a1,i2.2,/)') "Time Sum: ", &
timesum%hours, ":", timesum%minutes, ":", &
timesum%seconds
contains
! *******************************************************
! Subroutine to prompt for, read, and check
! a time (hours:minutes:seconds) in 24-hour format.
subroutine readtime ( timeval )
type(time), intent(out) :: timeval
do
! prompt for time
write (*,'(a)',advance="no") "Enter time (hh:mm:ss): "
! read time (hours, minutes, seconds)
read (*,*) timeval%hours, timeval%minutes, timeval%seconds
! check time entered
if ( timeval%hours >= 0 .and. timeval%hours <= 23.and. &
timeval%minutes >= 0 .and. timeval%minutes <= 59 &
.and. timeval%seconds >= 0 .and. &
timeval%seconds <= 59 ) exit
! display error message
write (*,'(a,/,a)') "Error, invalid time entered.", &
"Please re-enter time."
end do
return
end subroutine readtime
121
:hapter 1E K ;erived ;ata T'pes
! *******************************************************
! Subroutine to add two times.
! Ensures seconds and minutes are within range (0-59)
! Hours may exceed 23
! subroutine header and appropriate declarations
subroutine addtimes ( tm1, tm2, tmsum )
type(time), intent(in) :: tm1, tm2
type(time), intent(out) :: tmsum
! add the seconds, minutes, hours
tmsum%seconds = tm1%seconds + tm2%seconds
tmsum%minutes = tm1%minutes + tm2%minutes
tmsum%hours = tm1%hours + tm2%hours
! if minutes > 59, subtract 60 from seconds and add 1 to minutes
if (tmsum%seconds > 59) then
tmsum%seconds = tmsum%seconds - 60
tmsum%minutes = tmsum%minutes + 1
end if
! if minutes > 59, subtract 60 from minutes and add 1 to hours
if (tmsum%seconds > 59) then
tmsum%minutes = tmsum%minutes - 60
tmsum%hours = tmsum%hours + 1
end if
return
end subroutine addtimes
end program timeSummation
.f the program does not wor) at first, the comments can aid in determining the pro(lem.
1&.4.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the and entering a series of various time values to
ensure that the results are correct. .f the program does not wor) initiall', the functionalit' of each
su(routine should (e chec)ed. The times read from the user can (e displa'ed to the screen to ensure
the' are correct. =nce the times are correct, the add times su(routine can (e chec)ed. Each of the time
sums can (e displa'ed to help determine where the error might (e.
10.5 %rrays of #eri)ed #ata
.n addition to declaring single varia(les (ased on the derived data t'pe definition, it is possi(le to
declare an arra' (ased the derived data t'pe definition.
0or e+ample, to declare an arra' named class to hold 30 elements of t'pe student, the following
declaration can used used.
type(student), dimension(30) :: class
130
:hapter 1E M ;erived ;ata T'pes
Each element of the arra' class will (e of the t'pe student and include each of the defined components
3name, id, score, grade in this e+ample4.
0or e+ample, the la'out would (e as follows$
class314 name
id
score
grade
class324 name
id
score
grade
class334 name
id
score
grade
... ...
To access elements in the arra', an inde+ must (e used. ,fter the inde+, the desired component would
(e specified. 0or e+ample, to set values for the third student, the following statements could (e used.
class(3)%name = "Fred"
class(3)%id = 4321
class(3)%score = 75.75
class(3)%grade = "C"
,s with an' arra', the inde+ can (e an integer varia(le.
,s with single varia(les, it is possi(le to assign all components of an arra' element to another arra'
element or another varia(le of the same derived data t'pe. The following declarations and code could
(e used to swap the location of the fifth student and the eleventh student.
type student
character(50) :: name
integer :: id
real :: score
character(1) :: grade
end type student
type(student), dimension(30) :: class
type(student) :: temp
temp = class(5)
131
:hapter 1E K ;erived ;ata T'pes
class(5) = class(11)
class(11) = temp
This code fragment will cop' all components from the fifth arra' element 3of t'pe t'pe student4 into a
temporar' varia(le 3also of t'pe student4. Then, the eleventh arra' element can (e copied into the fifth
arra' element 3thus overwriting all previous values4. ,nd, finall', the eleventh arra' element can (e set
of the original values from the fifth arra' element which are held in the temporar' varia(le.
10.0 ,xam"le T*o
.n this e+ample, we will write a simple program to perform some processing for students. The student
information will (e stored in an arra' of derived data t'pes. There will (e no more than 50 students per
class. The main will call a su(routine to read student information 3name and score4 and another
su(routine to set the student grades. 0inall', the main will call a function to calculate the class average.
The main will displa' the average. *outines for displa'ing the students are left as an e+ercise.
1&.&.1 8n'erstan' the Problem
The main is e+pected to define the appropriate derived data t'pe for student, declare some varia(les of
that t'pe and call the su(routines. The first su(routine will read student information including a name
3up to E0 characters4 and score from the user. !ames and scores should continue to (e read until a
(lan) name is entered. The score value must (e (etween 0.0 and 100.0 3inclusive4. 0or this simple
e+ample, we will re6prompt for incorrect data entr' 3until correct data is provided4. The routine must
return the count of students entered. The second su(routine set the grades (ased on the following
standard scale.
, > : ; 0
,[U10 C0 6 C1 B0 6 B1 E0 6 E1 ZU51
8hen determining the final grade, the program should round up when appropriate. The main will call
a function to calculate and return the average of the scores. ,dditionall', the main will displa' the final
average.
1&.&.2 Create the 2lgorithm
0or this e+ample main part for the main include declaration, displa' header, call read time su(routine,
and the call the time summation su(routine. The (asic steps for the main include$
! define derived data type for student
! must include name, id, grade
! declare variables
! includes array for up to 50 students
! display initial header
! call subroutine to read student information
! call subroutine to set grades
! use function to calculate average of scores
! display average
132
:hapter 1E M ;erived ;ata T'pes
The (asic steps for the read student information su(routine include$
! subroutine header and appropriate declarations
! loop
! prompt for student name
! read name
! if name is empty, exit loop
! loop
! prompt for student score
! read score
! check score entered
! if [ score is between 0.0 and 100.0 (inclusive) ] exit
! display error message
! end loop
! update count of students
! place values in student array
! end loop
The (asic steps for the set grades su(routine include$
! subroutine header and appropriate declarations
! loop
! read score / set grade
! 90 A; 80 - 89 B; 70 79 C; 60 - 69 D; 59 F
! end loop
8hen determining the final grade, the nearest integer intrinsic function, nint34, can (e used to perform
the appropriate rounding.
The (asic steps for the calculate average score function include$
! function header and appropriate declarations
! loop
! sum scores
! end loop
! calculate and return average
0or convenience, the steps are written a program comments.
1&.&.3 De4elop the Program
>ased on the algorithm, the (elow program could (e developed.
program classScores
! define derived data type for student, includes name, id, grade
implicit none
type student
character(60) :: name
real :: score
character(1) :: grade
end type
133
:hapter 1E K ;erived ;ata T'pes
! declare variables, including array for up to 50 students
type(student), dimension(50) :: class
integer :: count
real :: average
! display initial header
write (*,'(/,a,/)') "Student Information Example Program."
! call subroutine to read student information
call readStudents (class, count)
! call subroutine to set grades
call setStudentGrades (class, count)
! use function to calculate average of scores
average = classAverage (class, count)
! display average
write (*,'(/,a, f5.1)') "Final Class Average: ", average
contains
! *******************************************************
! Subroutine to read student information (name and score).
! A blank name will stop input
! The score must be between 0.0 and 100.0 (inclusive)
subroutine readStudents (class, count)
type(student), dimension(50), intent(out) :: class
integer, intent(out) :: count = 0
character(60) :: tempname
real :: tempscore
do
! prompt for student name and read name
write (*,'(a)',advance="no") "Enter Student Name: "
read (*,'(a60)') tempname
! if name is empty, exit loop
if ( len_trim(tempname) == 0 ) exit
do
! prompt for student score and read score
write (*,'(a)',advance="no") "Enter Student Score: "
read (*,*) tempscore
! check score entered
if ( tempscore >= 0.0 .and. tempscore <= 100.0 ) exit
! display error message
write (*,'(a,/,a)') "Error, invalid score.", &
"Please re-enter time."
end do
13<
:hapter 1E M ;erived ;ata T'pes
! update count of students and place values in student array
count = count + 1
class(count)%name = tempname
class(count)%score = tempscore
end do
return
end subroutine readStudents
! *******************************************************
! Subroutine to set student grades.
! 90 A; 80 - 89 B; 70 79 C; 60 - 69 D; 59 F
subroutine setStudentGrades (class, count)
type(student), dimension(50), intent(inout) :: class
integer, intent(in) :: count
integer :: i
do i = 1, count
! read score / set grade
select case ( nint(class(i)%score) )
case (90:)
class(i)%grade = "A"
case (80:89)
class(i)%grade = "B"
case (70:79)
class(i)%grade = "C"
case (60:69)
class(i)%grade = "D"
case (:59)
class(i)%grade = "F"
end select
end do
return
end subroutine setStudentGrades
! *******************************************************
! Function to calculate average score.
real function classAverage (class, count)
type(student), dimension(50), intent(in) :: class
integer, intent(in) :: count
integer :: i
real :: sum = 0.0
! sum scores
do i = 1, count
sum = sum + class(i)%score
end do
! calculate and return average
135
:hapter 1E K ;erived ;ata T'pes
classaverage = sum / real(count)
return
end function classAverage
end program classScores
.f the program does not wor) at first, the comments can aid in determining the pro(lem.
1&.&.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the and entering a series of student data values to
ensure that the results are correct. .f the the program does not provide the correct results, each of the
su(routines and the function results should (e verified individuall'. Each can (e chec)ed (' displa'ing
the intermediate results to the screen. .n this manner, the su(routine or function that is not wor)ing
correctl' can (e Auic)l' identified. =nce identified, some additional write statements inside the
su(program can (e used to help identif' the specific pro(lem.
10.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
1&.5.1 Quiz Questions
>elow are some Aui@ Auestions.
14 ,n item in a derived data t'pe is calledN
24 How are components of a derived data t'pe accessedN
34 ;efine a derived data t'pe to store information a(out a circle. Iust include a circle name 3ma+
20 characters4, si@e 3radius D a real value4 and the position in 36dimensional space 3x, #, and z
Q all integer values4.
<4 8rite the declaration necessar' to declare two varia(les named circle1 and circle2 of t'pe
circle 3from previous Auestion4.
54 ;efine a user6defined t'pe, planet, to store information for a planet. .nclude a name 315
characters4, radius 3real value4, area 3real value4, and volume 3real value4. ,dditionall', write
the declaration necessar' to declare two varia(les named planet1 and planet2 of t'pe planet,
E4 ;efine a user6defined t'pe named date for processing dates consisting of a month name 310
characters4, month 3integer4, da' of month 3integer4, and 'ear 3integer4.
B4 >ased on the previous Auestion, write the statements to$
a4 declare a varia(le named toda# and set it to toda's date Q monthname 3character4, month,
date, and 'ear 3integers4
(4 declare a varia(le named new#ear and set it to Januar' 1, 2011 Q monthname 3character4,
month, date, and 'ear 3integers4
13E
:hapter 1E M ;erived ;ata T'pes
1&.5.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the time summation program, compile and e+ecute the program. Test on several sets of
input including the e+ample in the e+planation.
24 8rite a 0ortran program to read and displa' information a(out a(out a set of planetar' (odies.
The program should read the information from a file, allow the use to select a displa' option,
and call the appropriate routine to displa' that information.
The main program should call a series of su(routines as follows$
%u(routine readPlanets34 to prompt for file name of planets file, open the file 3including
error chec)ing4, and read file into an arra'. Three errors are allowed, (ut if a fourth
error is made, the routine should terminate the program.
%u(routine calcPlanetrea34 to calculate the planet area (ased on the diameters.
0unction get7ser'ption34 to displa' a list of options, read the selection option.
%u(routine displa#Planet5in5ax34 to displa' the minimum and ma+imum (ased on
option as follows$
=ption 314 Q %mallest and 9argest /lanets 3(ased on area4
=ption 324 Q :oldest and Hottest /lanets 3(ased on average temperature4
=ption 334 Q /lanets with %hortest and 9ongest ;a's 3(ased on da' length4
%u(routine printPlanets!ummar#34 to displa' the planet name, distance from sun, and
planet si@e.
The output should (e formatted as appropriate. Test on several sets of input values and verif'
that the output is correct for the given input values.
34 Iodif' the planet program 3from previous Auestion4 to sort the planets (ased on the radius. Test
on several sets of input values and verif' that the output is correct for the given input values.
<4 T'pe in the time class scores program, compile and e+ecute the program. Test on several sets of
input values.
13B
:hapter 1E K ;erived ;ata T'pes
54 Iodif' the class scores program to assign grades (ased on the following scale$
F D C4 C C< #4 # #< .4 . .<
,4! (,47, 7,472 7347( 7747 *,4*2 *34*( *74* ,42 34( 741,,
Test on several sets of input values and verif' that the output is correct for the given input
values.
E4 Iodif' the class scores program to read the name and score file a file. %hould include
prompting for a file, opening the file, and reading the file contents into the class arra'. .n order
to complete this e+ercise, create a file containing some random names and scores. Test on
several sets of input values.
13C
15 4odules
0or larger programs, using a single source file for the entire program (ecomes more difficult.
0ortunatel', large programs can (e split into multiple source files, each file can contain a su(set of
su(routines and5or functions. There must (e a main or primar' source file that includes the main
program. The secondar' file or files is referred to as a module or modules. ,dditionall', the modules
can then (e more easil' used in other, different programs ensuring that the code can (e easil' re6used.
This saves time and mone' (' not re6writing routines.
This section provided a description of the formatting reAuirements and an e+ample of how to set6up the
modules.
15.1 4odule #eclaration
The secondar' source file or module must (e formatted in a specific manner as follows$
module <name>
<declarations>
contains
<subroutine and/or function definitions>
end module <name>
0or e+ample, to declare a module named stats that includes some a function to find the average of the
num(ers in an arra', the following module declaration might (e used.
module stats
! note, no global variables used in this module
contains
! *************************************************************
! Simple function to find average of len values in an array.
real function average(array, len)
real, intent(in), dimension(1000) :: array
integer, intent(in) :: len
integer :: i
real :: sum = 0.0
do i = 1, len
sum = sum + array(i)
end do
average = sum / real(len)
end function average
end module stats
131
:hapter 1B K Iodules
This e+ample assumes the real arra' contains len num(er of values up to a ma+imum of 1000 values.
15. 6se 'tatement
=nce the module is defined, the routines from the module can (e included (' using the u$e statement.
The use statement or statements must (e at the (eginning of the applica(le source file. 0or e+ample,
(elow is a simple main that uses the previous stats module.
program average
use stats
implicit none
real, dimension(1000) :: arr
integer :: i, count
real :: ave
! -----
! Initialize array with some values.
count = 0
do i = 1, 20
arr(i) = real(i) + 10.0
count = count + 1
end do
! -----
! Call function to find average and display result.
ave = arraverage(arr, count)
write (*, '(/, a, f10.2, /)') "Average = ", ave
end program average
The use statement is included (efore the varia(le declarations. ,n' num(er of use statements for
defined modules ma' (e included.
15.! 6"dated Com"ilation Commands
0or a large program that is split (etween multiple source files, the compilation process must (e
updated. The compilation process refers to the steps reAuired to compile the program into a final
e+ecuta(le file. Each module unit must (e compiled independentl'. This allows the programmer to
focus on one module, set of routines, at a time. 0urther, for ver' large proFects, multiple programmers
can wor) on separate modules simultaneousl'.
The initial step is to compile each module. ,ssuming the module from the earlier section is named
stats.f95, the command to compile a module is$
gfortran -c stats.f95
which will read the source file 3stats.f954 and create two new filesP an o(Fect file stats.o and a
1<0
:hapter 1B M Iodules
module file stats.mod. The name of the o(Fect file is (ased on the name of the source file. The
name of the module file is (ased on the module name. 8hile the' are the same name in this e+ample,
that is not a reAuirement.
The compile command is reAuired for each module.
=nce all the modules are compiled and the .o and .mod files are availa(le, the main file can (e
compiled. This step reads the .o and .mod files for each module and (uilds the final e+ecuta(le file.
0or e+ample, the command to compile the main file for the previous arra' average e+ample is$
gfortran -o main main.f95 stats.o
0or multiple modules, each of the .o files would (e listed. .n this e+ample, the stats.mod file is read
(' the gfortran compiler. 8hile not e+plicitl' listed, the .mod files are reAuired and used at this
step.
15.$ 4odule ,xam"le Program
The following is an e+ample program to compute the surface area and volume of a sphere. This is a
fairl' straightforward pro(lem focusing more on the creation and use of a module for some routines.
15.4.1 8n'erstan' the Problem
This pro(lem will (e divided into two parts, the main program source file and a secondar' source file
containing the su(routines and functions. 8hile this pro(lem is not large enough to reAuire splitting
into multiple files, it is split to provide an e+ample of how to use modules.
*ecall that the formulas for the surface area and volume of a sphere are as follows$
surfaceArea = 4.0 radius
2
volume =
4.0
3.0
radius
3
The value of ; will (e defined as a constant and set to 3.1<151.
0or this e+ample, the main program will displa' some initial headers and read the radius from the user.
=nce the radius is read, the main program will call functions for the surface area and the volume and a
su(routine to displa' the results.
15.4.2 Create the 2lgorithm
>ased on the pro(lem definition, the steps for the main are$
! display header and read radius
! call functions for sphere volume and surface area
! call routine to display formatted results
The module will contain the functions and su(routine. The first function will compute the sphere
1<1
:hapter 1B K Iodules
volume. The single step is$
! compute the volume of a sphere with given radius.
! sphere volume = [ (4.0 * pi) / 3.0 ] * radius^3
The second function will compute the sphere surface area. The single step is$
! compute the volume of a sphere with given radius
! sphere volume = 4.0 * pi * radius^2
The su(routine will displa' the formatted results.
15.4.3 De4elop the Program
The program is presented in two parts corresponding to the main program and the secondar' module
routines. 8hile this e+ample is not reall' long or comple+ enough to reAuire multiple files, the
program is split in order to provide an e+ample using a separate module file.
15.4.3.1 3ain Program
>ased on the algorithm, the (elow program could (e developed.
program sphere
use sphereRoutines
implicit none
real :: radius, spVolume, spSurfaceArea
! -----
! Display header and read radius
write (*,'(a/)') "Sphere Example Program"
write (*,'(a)', advance="no") "Radius: "
read (*,*) radius
! -----
! Call functions for sphere volume and surface area
spVolume = sphereVolume(radius)
spSurfaceArea = sphereSurfaceArea(radius)
! -----
! Call routine to display formatted results.
call displayResults(radius, spVolume, spSurfaceArea)
end program sphere
The name of module, sphereRoutines in this e+ample, must (e the name of the secondar' source
file.
1<2
:hapter 1B M Iodules
15.4.3.2 3o'ule Routines
>ased on the algorithms for the two functions and su(routine, the (elow module program could (e
developed. .n this e+ample, the declaration for ; is defined as a glo(al varia(le. This shares the
varia(le (etween all the su(routines and functions in the module. "se of glo(al varia(les is t'picall'
limited. This provided an e+ample of an appropriate use of a glo(al varia(le.
! Example secondary source file.
module sphereRoutines
implicit none ! needed in every module
! Global declarations, if any, go here.
real, parameter :: pi = 3.14159
! ********************************************************
! Subroutines and functions are included after
! the 'contains'.
contains
! ********************************************************
! Compute the volume of a sphere with given radius.
! sphere volume = [ (4.0 * pi) / 3.0 ] * radius^3
real function sphereVolume (radius)
real, intent(in) :: radius
sphereVolume = ( ( 4.0 * pi ) / 3.0 ) * radius ** 3
end function sphereVolume
! ********************************************************
! Compute the volume of a sphere with given radius.
! sphere volume = 4.0 * pi * radius^2
real function sphereSurfaceArea (radius)
real, intent(in) :: radius
sphereSurfaceArea = 4.0 * pi * radius ** 2
end function sphereSurfaceArea
! ********************************************************
! Simple routine to display results.
subroutine displayResults(rad, vol, area)
real, intent(in) :: rad, vol, area
write (*,'(/, a)') "-------------------------------"
write (*, '(a)' ) "Results:"
write (*,'(3x, a, f10.2)') "Sphere Radius = ", rad
write (*,'(3x, a, f10.2)') "Sphere Volume = ", vol
1<3
:hapter 1B K Iodules
write (*,'(3x, a, f10.2, /)') "Sphere Surface Area = ", area
end subroutine displayResults
! ********************************************************
end module sphereRoutines
.n a more comple+ program multiple module files might (e used. The grouping should (e (ased on the
logical relationship of the routines. , more complicated program would reAuire a more comprehensive
design effort.
15.4.4 0est9Debug the Program
0or this pro(lem, the testing would involve e+ecuting the and entering a series of radius values and
ensure that the results are correct. .f the the program does not provide the correct results, each of the
functions and the su(routines could (e verified individuall'. Each can (e chec)ed (' displa'ing the
intermediate results to the screen. .n this manner, the su(routine or function that is not wor)ing
correctl' can (e Auic)l' identified. =nce identified, some additional write statements inside the
su(program can (e used to help identif' the specific pro(lem.
15.5 ,xercises
>elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.
15.-.1 Quiz Questions
>elow are some Aui@ Auestions.
14 8hat is the primar' purpose of using a moduleN
24 .n the main program, what statement is used to include the modulesN
34 How man' main programs are allowedN
<4 How man' modules are allowedN
54 .s the contains )e' word needed in a module file 3'es or no4N
15.-.2 uggeste' Pro(ects
>elow are some suggested proFects.
14 T'pe in the arra' average main program and the arra' average module, compile and e+ecute the
program. Test on several sets of input including the e+ample in the e+planation.
24 T'pe in the sphere volume and surface area main program and the sphere volume and surface
area module, compile and e+ecute the program. Test on several sets of input including the
e+ample in the e+planation.
34 "pdate the planets program form the previous chapter, pro(lem a2, and (rea) the program into
a main file and a module file for the functions and su(routines.
1<<
18 %""endix % 1 %'CII Table
This ta(le lists the ,merican %tandard :ode for .nformation .nterchange 3,%:..4 characters or
s'm(ols and their decimal num(ers.
Char. Dec. Char. Dec. Char. Dec.
32 H (4 I (
F 33 . (! a 7
J 34 # (( 0 *
K 3! C (7 c
L 3( D (* d 1,,
M 37 % ( e 1,1
N 3* F 7, : 1,2
O 3 G 71 g 1,3
@ 4, ? 72 h 1,4
A 41 I 73 i 1,!
= 42 P 74 Q 1,(
< 43 9 7! R 1,7
S 44 + 7( & 1,*
4 4! / 77 m 1,
. 4( 7 7* n 11,
- 47 O 7 o 111
, 4* ) *, p 112
1 4 T *1 D 113
2 !, 6 *2 r 114
3 !1 S *3 $ 11!
4 !2 1 *4 t 11(
! !3 5 *! u 117
( !4 8 *( v 11*
7 !! 2 *7 3 11
* !( G ** ' 12,
!7 U * y 121
V !* E , z 122
W ! X 1 Y 123
C (, Z 2 [ 124
> (1 \ 3 ] 12!
B (2 ^ 4 _ 12(
` (3 a ! 127
1<5
:hapter 1C K ,ppendi+ , D ,%:.. Ta(le
1<E
19 %""endix 2 1 Windo*s 'tart<6" Instructions
The following provides some specific instructions for getting started. These instructions are
specificall' geared for using a 8indows (ased /:s. This includes all versions of 8indows from
8indows J/, 8indows Vista, 8indows B, and 8indows C.
The (asic process is ver' similar to I,: and 9inu+ 3which is not covered here4.
19.1 Wor/ing Files
>efore wor)ing with 0ortran program files, 'ou should decide where 'ou will (e wor)ing 3:d$ drive,
"%> drive, networ) drive, etc.4 and create a wor)ing director' where 'our files will (e placed. .n
general, it will (e easier if 'our 0ortran files are not mi+ed with other, unrelated files. This director'
should (e someplace 'ou can easil' get to it. That might (e on 'our home wor)station5laptop, on a
networ) drive, or on a "%> drive.
19. &btaining The Com"iler
0irst, 'ou will need to download and install the !" 0ortran compiler. The main we( page for the
!" 0ortran compiler is$
http$55gcc.gnu.org5fortran5
This page provides general information regarding the 0ortran compiler development effort, proFect
o(Fectives, and current status.
Iore specific information, and the 8indows compiler (inaries, can (e found on the g0ortran 8i)i
page, which is located at$
http$55gcc.gnu.org5wi)i50ortran
This page contains lin)s to the fortran (inaries. =n this page, clic) on the lin) la(eled$
>inaries for 8indows, 9inu+, and Iac=%
8hich will displa' the page for the !">inaries for various platforms, including 8indows, Iac=%,
and 9inu+. :lic) on the 8indows lin), which will show the various 8indows options. 0or standard
8indows 3J/5Vista5B5C4, the heading /inG2 0ui&d 3-native 8indows2 (uild4, includes a lin) for the
latest installer. :lic) on the lin) and download the 8indows installation program. #ou will need to
access this file to perform the actual installation.
This version will wor) on all supported 8indows versions including 8indows B and 8indows C.
,fter downloading, install the compiler. The installation can (e accomplished (' dou(le6clic)ing on
the downloaded file. ,s with all 8indows installs, it will reAuire %'stem ,dministrator privileges.
1<B
:hapter 11 K ,ppendi+ > D 8indows %tart6"p .nstructions
19.! Command Prom"t
.n order to compile and wor) with programs under 8indows, we will need to provide t'ped commands
to the computer. This is done from within the -:ommand /rompt2 utilit'.
1:.3.1 =in'o+s >P9)ista95
.n 0or 8indows B, the -:ommand /rompt2 is usuall' under )rogram$ Q .cce$$orie$ Q Command
)rompt.
1:.3.2 =in'o+s 6
0or 8indows C, the -:ommand /rompt2 can (e found (' using %earch and is listed under the
2indo3$ Sy$tem heading.
1:.3.3 Comman' Prompt =in'o+
The open :ommand /rompt window for an' 8indows version will loo) similar to the following$
=nce the :ommand /rompt is open, the device and director' for the wor)ing files can (e set.
1:.3.4 De4ice an' Directory
.n order to compile and wor) with programs under 8indows, a wor)ing director' should (e
esta(lished. This is where the program files will (e stored. 0irst, esta(lish the device of the wor)ing
director'. .f the files are on :$d 3the main hard drive4, the device is alread' set. .f the wor)ing
director' is located on a networ) drive, alternate drive, or "%> drive, the device will need to (e set.
"sing the -I' :omputer2, determine the device or drive letter where 'ou director' is located. T'pe
that letter at the prompt in the :ommand /rompt window. 0or e+ample, if 'our device is 9, 'ou would
t'pe -RV2.
,t the -G$d[2 'ou will need to change director' into the director' where 'our files are 3if 'ou created
one4. The -cd ZdirRname[2 command can (e used. 0or e+ample, if the director' is named cs11B, the
command would (e -cd c$1172.
1<C
:hapter 11 M ,ppendi+ > D 8indows %tart6"p .nstructions
0or e+ample$
C:\Documents and Settings\Ed\My Documents> k:
K:\> cd cs117
,t this point, t'ping dir 3for director'4 will provide a list of files in the director'. 8hile the format
will appear different, the files are the same as shown in the /y Computer listing.
19.$ Com"iler Installation 3erification
To ensure the compiler is installed correctl', open the -:ommand /rompt2, and t'pe g:ortran at the
prompt.
K:\cs117> gfortran
gfortran: no input files
The -no input files2 message means that the installation was completed correctl'. .t is not necessar' to
set the device or director' in order to perform this verification.
However, if the following message is displa'ed,
K:\cs117> gfortran
'gfortran' is not recognized as an internal or external command,
operable program or batch file.
means that the 0ortran compiler is not installed. The installation issue must (e addressed (efore
continuing. =nce the installation is completed successfull', the compilation steps detailed in :hapter 3
can (e completed.
19.5 Com"ilation
=nce the 0ortran compiler is installed, programs can (e compiled. =pen the -:ommand /rompt2, and
set the device and director' as appropriate.
,t this point the program can (e compiled, using -gfortran. The optional -6o2 Aualifier is used to set
the name of the output file. To e+ecute, 'ou can t'pe the name of the e+ecuta(le 3that was specified
with the -6o24.
To compile the e+ample program, the following command would (e entered$
K:\cs117> gfortran -o hw hw.f95
This command will tell the 7gfortran7 compiler to read the file hw.f95 and, if there are no errors,
create an e+ecuta(le file named hw.exe. .f there is an error, the compiler will generate an error
message, sometimes cr'ptic, and provide a line num(er. %uch errors are usuall' the result of mist'ping
one of the instructions. ,n' errors must (e resolve (efore continuing.
1<1
:hapter 11 K ,ppendi+ > D 8indows %tart6"p .nstructions
19.0 ,xecuting
To e+ecute or run a program, t'pe the name of the e+ecuta(le file. 0or e+ample, to e+ecute or run the
hw.exe program$
K:\cs117> hw
Hello World
K:\cs117>
8hich will e+ecute the e+ample program and displa' the -Hello 8orld2 message to the screen.
19.5 ,xam"le
, more complete e+ample is as follows$
.t is not necessar' to t'pe the e+tension 3i.e., -.e+e24 portion of the file name.
150
; %""endix C 1 +andom =umber -eneration
enerating random num(ers is a common reAuirement for man' pro(lems. The following provides a
summar' of utili@ing the (uilt6in 0ortran random num(er generator routines.
;.1 Initiali(ation
The first step in generating random num(ers is to initiali@e the 0ortran random num(er generator,
randomRseed34. The most (asic initiali@ation is performed as follows$
call random_seed()
This will initiali@e the random num(er generator with a default seed. ,s such, each e+ecution will re6
generate the same series of random num(ers for each e+ecution. 8hile this ma' not appear ver'
random, since successive e+ecutions generate the same series of random num(ers, the testing is more
repeata(le.
;. -enerating +andom =umber
To reAuest a random num(er, a real varia(le must (e declared and then passed to the following call to
the (uilt6in randomRnum(er34 routine. 0or e+ample$
call random_number(x)
The random num(er (etween 0.0 and 1.0 such that 0.0 _ random num(er Z 1.0.
.n order to o(tain a larger num(er, it can (e multiplied (' an appropriate scale. 0or e+ample, to
simulating the roll of a dice, a random integer num(er (etween 1 and E would (e reAuired. The
following code would o(tain the random num(er and then scale it and convert to integer as reAuired.
call random_number(x)
die = int(x*6.0) + 1
%ince the 0.0 is a possi(le value and 1.0 is not 3 0.0 _ random num(er Z 1.04 1 is added to ensure that 0
can not (e assigned to the varia(le die. 0urther, since .111 is the largest possi(le value 3since 1.0 is
not4, and .111 Y E will generate E 35.1 truncated to 5 with 1 added4.
151
:hapter 20 K ,ppendi+ : D *andom !um(er eneration
;.! ,xam"le
, simple e+ample program to generate 1000 random integer num(ers, each (etween 1 and 100, is as
follows$
program rand
implicit none
integer, parameter :: rcount=1000
integer :: i
integer, dimension(rcount) :: nums
real :: x
call random_seed()
do i = 1, rcount
call random_number(x)
nums(i) = int(x*100.0) + 1
end do
write (*,'(a)') "Random Numbers:"
do i = 1, rcount
write (*,'(i3,2x)', advance="no") nums(i)
if (mod(i,10)==0) write(*,*)
end do
end program rand
The call to randomRseed34 must (e performed (efore the call to randomRnum(er34. ,dditionall', the
call to randomRseed34 can onl' (e performed once.
The output of this e+ample program is shown (elow$
Random Numbers:
100 57 97 75 37 49 8 1 35 35
22 14 91 39 45 67 2 66 65 33
86 41 21 97 60 68 46 34 11 76
61 72 90 66 16 62 98 100 26 56
66 56 98 91 66 73 41 93 15 68
77 34 12 62 83 95 74 50 38 43
56 100 100 75 96 10 74 76 95 71
82 56 7 49 60 14 59 52 89 31
67 67 51 27 8 11 55 38 2 80
63 78 96 12 32 60 5 12 22 11
Each e+ecution will generate the same series of random num(ers.
;.$ ,xam"le
.n order to generate different random num(er for successive e+ecutions, the seed must (e initiali@ed
with a different set of seed values each time.
152
:hapter 20 M ,ppendi+ : D *andom !um(er eneration
The following e+ample simulates the roll of two dice, which reAuires two random integer num(ers,
each (etween 1 and E.
program diceRoll
implicit none
integer :: m, die1, die2, pair
real :: x
integer :: i, n, clock
integer, dimension(:), allocatable :: seed
character(10) :: nickname
call random_seed(size = n)
allocate(seed(n))
call system_clock(count=clock)
seed = clock + 37 * (/(i-1, i=1, n)/)
call random_seed(put = seed)
deallocate(seed)
call random_number(x)
die1 = int(x*6.0) + 1
call random_number(x)
die2 = int(x*6.0) + 1
write (*,'(2(a,1x,i1/),a,1x,i2)') "Dice 1:", die1, &
"Dice 2:", die2, "Dice Sum", (die1+die2)
end program diceRoll
8ill generate different values each e+ecution. 0or e+ample, three e+ecutions of the e+ample program
are shown (elow$
C:\fortran> dice
Dice 1: 5
Dice 2: 4
Dice Sum 9
C:\fortran> dice
Dice 1: 2
Dice 2: 4
Dice Sum 6
C:\fortran> dice
Dice 1: 1
Dice 2: 6
Dice Sum 7
C:\fortran>
The dice values will (e different for each e+ecution.
153
:hapter 20 K ,ppendi+ : D *andom !um(er eneration
15<
1 %""endix # 1 Intrinsic Functions
The following is a partial listing of the 0ortran 15 intrinsic functions. =nl' the most common intrinsic
functions are included in this section. , complete list can (e found on6line at the !" 0ortran
documentation we( page.
1.1 Con)ersion Functions
The following ta(le provides a list of intrinsic functions that can (e used for conversion (etween
different data t'pes.
Function De$cription
.!T3,4 *eturns integer value of real argument ,, truncating 3real
part4 towards @ero.
!.!T3J4 *eturn nearest integer value 3with appropriate rounding
up or down4 of the real argument J.
*E,93,4 *eturns the real value of integer argument ,.
1. Integer Functions
The following ta(le provides a list of intrinsic functions that can (e used for integers.
Function De$cription
,>%3,4 *eturns integer a(solute value of integer argument ,.
I=;3*1,*24 *eturn the integer remainder of integer argument *1
divided (' integer argument *2.
155
:hapter 21 K ,ppendi+ ; D .ntrinsic 0unctions
1.! +eal Functions
The following ta(le provides a list of intrinsic functions that can (e used for reals.
Function De$cription
,>%3,4 *eturns real a(solute value of real argument ,.
,:=%384 *eturns real inverse cosine of real argument 8 in radians.
,%.!384 *eturns real inverse sine of real argument 8 in radians.
,T,!3J4 *eturns real inverse tangent of real argument J in radians.
:=%384 *eturns real cosine of real argument 8 in radians.
9=384 *eturns real natural logarithm of real argument 8. *eal
argument 8 must (e positive.
I=;3*1,*24 *eturn the real remainder of real argument *1 divided ('
real argument *2.
%.!384 *eturns real sine of real argument 8 in radians.
%?*T384 *eturns real sAuare root of real argument 8. *eal
argument 8 must (e positive.
T,!3J4 *eturns real tangent of real argument J in radians.
1.$ Character Functions
The following ta(le provides a list of intrinsic functions that can (e used for characters5strings.
Function De$cription
,:H,*3.4 *eturns the character represented (' integer argument .
(ased on the ,%:.. ta(le 3,ppendi+ ,4. .nteger argument .
must (e (etween 1 and 12B.
.,:H,*3:4 *eturns the integer value of the character argument :
represented (' ,%:.. ta(le 3,ppendi+ ,4.
9E!3%T*4 *eturns an integer value representing the length of string
argument %T*.
9E!RT*.I3%T*4 *eturns an integer value representing the length of string
argument %T* e+cluding an' trailing spaces.
9E3%T*1,%T*24 *eturns logical true, if %T*1 e %T*2 and false otherwise.
9T3%T*1,%T*24 *eturns logical true, if %T*1 [ %T*2 and false otherwise.
99E3%T*1,%T*24 *eturns logical true, if %T*1 _ %T*2 and false otherwise.
99T3%T*1,%T*24 *eturns logical true, if %T*1 [ %T*2 and false otherwise.
T*.I3%T*4 *eturns string (ased on the string argument %T* with an'
trailing spaces removed.
15E
:hapter 21 M ,ppendi+ ; D .ntrinsic 0unctions
1.5 Com"lex Functions
The following ta(le provides a list of intrinsic functions that can (e used for comple+ num(ers.
Function De$cription
,.I,3W4 *eturns the real value of the imaginar' part of the comple+
argument W.
:I/9J3J,#4 *eturns comple+ value with real argument J and the real
part and real argument # as the imaginar' part.
*E,93,4 *eturns the real value of the real part of the comple+
argument W.
1.0 %rray Functions
The following ta(le provides a list of intrinsic functions that can (e used for arra's.
Function De$cription
I,J9=:3,14 *eturns integer location or inde+ of the ma+imum value in
arra' ,1.
I,JV,93,14 *eturns ma+imum value in arra' ,1. T'pe of value
returned is (ased on the t'pe of the argument arra' ,1.
I.!9=:3,14 *eturns integer location or inde+ of the minimum value in
arra' ,1.
I.!V,93,14 *eturns minimum value in arra' ,1. T'pe of value
returned is (ased on the t'pe of the argument arra' ,1.
%"I3,14 *eturns sum of values in arra' ,1. T'pe of value returned
is (ased on the t'pe of the argument arra' ,1.
15B
:hapter 21 K ,ppendi+ ; D .ntrinsic 0unctions
1.5 'ystem Information Functions
The following ta(le provides a list of intrinsic functions that o(tain information from the s'stem.
Function De$cription
:=II,!;R,*"IE!
TR:="!T34
*eturns the num(er of command line arguments.
ETR:=II,!;R,*
"I!E!T3!"I>E*,
V,9"E, 9E!TH,
%T,T"%4
*eturns command line arguments, if an'.
!"I>E*, integer argument of the num(er to
return. Iust (e (etween 1 and
:=II,!;R,*"IE!TR:="!T34.
V,9"E, character3Y4, !
th
argument
9E!TH, integer, length of argument returned in
V,9"E
%T,T"%, integer, status, 0Usuccess and 61UV,9"E
character arra' is too small for argument, other
valuesUretrieval failed
:/"RT.IE3T.IE4 *eturns the amount of :/" time e+pended on the current
program in seconds. T.IE is return as a real value.
;,TER,!;RT.IE
3;,TE,
T.IE,W=!E,V,9"E%4
*eturn date and time.
;,TE34, character3C4, string in the form
####II;;, where #### is 'ear, II is
month, and ;; is date.
T.IE34, character3104, string in the form
HHII%%.%%% where HH is hour, II is minute,
%% is second, and %%% is millisecond.
W=!E34, character354, string in the form of
fHHII, where HHII is the time difference
(etween local time and :oordination "niversal
Time.
V,9"E%34, integer arra' where
V,9"E%314 Q 'ear
V,9"E%324 Q month 316124
V,9"E%334 Q date 316314
V,9"E%3<4 Q month 316124
V,9"E%354 Q hour 306234
V,9"E%3E4 Q Time @one difference 3minutes4
V,9"E%3B4 Q seconds 306514
V,9"E%3C4 Q milleseconds 3061114
Each argument is optional, (ut at least one argument must
(e included
15C
%""endix , 1 3isuali(ation *ith -=6"lot
The 0ortran language does not have an' (uilt6in graphics capa(ilities. To support some (asic data
visuali@ation a plotting application, !"plot, can (e used. !"plot is a free, open source plotting
program that can plot data files and displa' user6defined functions.
This appendi+ provides a ver' (rief summar' of some of the (asic !"plot functions as applied to
plotting data from simple programs in this te+t. ,n general e+ample program to plot a simple function
is provided for reference.
.1 &btaining -=6"lot
The first step is to o(tain and install !"plot.
!"plot is availa(le at,
http://www.gnuplot.info/
To ensure that !"plot is installed correctl', for 8indows machine, 'ou can enter command prompt
and t'pe,
wgnuplot
which will start !"plot (' opening a new window. To e+it, t'pe e'it at the prompt.
:omplete documentation, tutorials, and e+amples are availa(le at that site. ,dditionall', there are
man' other we( site dedicated to !"plot.
. Formatting Plot Files
%ince our specific use of !"plot will involve plotting a data file created with a 0ortran program, it
will (e necessar' to provide some information and directions for !"plot in the file. That information
is provided in a header 3first few lines4 and a footer 3last few lines4. ,s such, the program must first
write the header, write the data, t'picall' in the form of data points to (e plotted, and write a final
footer. The header and footer ma' (e ver' different (ased on what is (eing plotted.
151
:hapter 22 K ,ppendi+ E D Visuali@ation with !"plot
22.2.1 /ea'er
The header will provides some guidelines on how the output should loo), including title 3if an'4, a+ises
3if an'4, la(les 3if an'4, and plotting color3s4. ,dditionall', comments can (e included with a -a2
character. :omments are useful to provide information a(out the contents of the plot file or nature of
the data (eing plotted. , t'pical header might (e as follows$
# Example Plot File
set title "CS 117 Plot Function"
plot "-" notitle with dots linewidth 2 linecolor 2
=nce the header is written, a series of data points can (e written.
22.2.2 %ooter
The footer is used to formall' tell !"plot there are no more points. ,dditionall', the -pause2
directive can (e used to ensure that an' plots displa'ed from the command line are left on the screen.
, t'pical footer might (e as follows$
end
pause -1
!othing after the footer will (e read (' !"plot.
.! Plotting Files
.n order to displa' a plot file on a 8indows machine, at the command prompt, t'pe,
wgnuplot file.plt
which will start !"plot and instruct !"plot to read the file -file.plt2. The file name can (e
an'thing and the file e+tension is not reAuired to (e -.plt2.
.f the header or footer commands are incorrect or the data points are invalid, nothing will (e displa'ed.
To investigate, the file can (e opened with a te+t editor.
.$ ,xam"le
This section provides an e+ample program that plots a simple function.
# = $in( x)
(
1co$( x)
3.,
)
The program, data file, and final output are presented for reference.
1E0
:hapter 22 M ,ppendi+ E D Visuali@ation with !"plot
22.4.1 Plot Program
The following is an e+ample program that generates points, opens a plot file, write the header, data
points, and footer.
program plotExample
implicit none
real, dimension(200) :: x, y
integer :: i, opnstat
! Generate x and y points
do i = 1, 200
x(i) = i * 0.05
y(i) = sin(x(i)) * (1-cos(x(i)/3.0))
end do
! Output data to a file
open (12, file="data.plt", status="replace", &
action="write", position="rewind", &
iostat=opnstat)
if (opnstat > 0) stop "error opening plot file."
! Write header
write (12, '(a)') "# Example Plot File"
write (12, '(a)') "set title ""Example Plot Function"" "
write (12,'(a,a)') "plot ""-"" notitle with dots ",
"linewidth 2 linecolor 2"
! Write points to file.
do i=1,100
write(12,*) x(i), y(i)
end do
! Write footer and close file
write (12, '(a)') "end"
write (12, '(a)') "pause -1"
close(12)
end program plotExample
The data file name can (e changed or read from the user.
1E1
:hapter 22 K ,ppendi+ E D Visuali@ation with !"plot
22.4.2 Plot %ile
The output file this program appears as follows$
# Example Plot File
set title "Example Plot Function"
plot "-" notitle with dots linewidth 2 linecolor 2
5.0000001E-02 6.9413913E-06
0.1000000 5.5457884E-05
0.1500000 1.8675877E-04
0.2000000 4.4132397E-04
0.2500000 8.5854460E-04
gman% points not displa%ed due to space considerationsh
4.900000 -1.043852
4.950000 -1.048801
5.000000 -1.050716
end
pause -1
The output file can (e edited with a standard te+t editor. This will allow chec)ing the data file for
possi(le errors if it does not displa' correctl'.
22.4.3 Plot !utput
The plot output is as follows$
=n 8indows machines, the plot can (e printed (' right clic)ing on the (lue (ar 3on top4. This will
displa' a menu, with -/rint2 as one of the options.
1E2
! %""endix F 1 Fortran 95 >ey*ords
.n programming, a )e'word is a word or identifier that has a special 0ortran 15 meaning. Ge'words are
reserved in that the' can not (e used for an'thing else such varia(le names.
The 8#pe as listed in the ta(le refers to the following$
statement Q implies a )e'word that starts a statement, usuall' one line unless there is a
continuation LXL
construct Q implies multiple lines, usuall' ending with Lend bL
attri(ute Q implies it is used in a statement to further clarif' or specif' additional
information.
0or reference, (elow is a partial list of )e'words or reserved words. 0or a complete list of )e'words,
refer to the on6line !" 0ortran 15 documentation.
9ey3ord 1ype /eaning
a&&ocata0&e attri(ute no space allocated here later allocate
a&&ocate statement allocate memor' space now for varia(le
a$$ignment attri(ute means su(routine is assignment 3U4
0acR$pace statement (ac) up one record
ca&& statement call a su(routine
ca$e statement used in select case structure
character statement intrinsic data t'pe
c&o$e statement close a file
comp&e' statement intrinsic data t'pe
contain$ statement internal su(routines and functions follow
cyc&e statement continue the ne+t iteration of a do loop
dea&&ocate statement free up storage used (' specified varia(le
de:au&t statement in a select case structure 6 all others
do construct start a do loop
e&$e construct part of if, else if, else, end if
e&$e i: construct part of if, else if, else, end if
e&$e3here construct part of where, elsewhere, end where
end do construct ends do loop
end :unction construct ends function
1E3
:hapter 23 K ,ppendi+ 0 D 0ortran 15 Ge'words
end i: construct ends if
end inter:ace construct ends interface
end modu&e construct ends module
end program construct ends program
end $e&ect construct ends select case
end $u0routine construct ends su(routine
end type construct ends t'pe
end 3here construct ends where
end:i&e statement mar) the end of a file
e'it statement continue e+ecution outside of a do loop
:ormat statement defines a format
:unction construct starts the definition of a function
i: statement and
construct
if3...4 statement
imp&icit statement LnoneL is preferred to help find errors
in a )e'word for
intent
the argument is read onl'
inout a )e'word for
intent
the argument is read5write
integer statement intrinsic data t'pe
intent attri(ute intent3in4 or intent3out4 or intent3inout4
inter:ace construct (egins an interface definition
intrin$ic statement sa's that following names are intrinsic
inDuire statement get the status of a unit
Rind attri(ute sets the )ind of the following varia(les
&en attri(ute sets the length of a character string
&ogica& statement intrinsic data t'pe
modu&e construct (eginning of a module definition
name&i$t statement defines a namelist of input5output
nu&&i:y statement nullif' a pointer
on&y attri(ute restrict what comes from a module
open statement open or create a file
operator attri(ute indicates function is an operator li)e O
optiona& attri(ute a parameter or argument is optional
out a )e'word for
intent
the argument will (e written
1E<
:hapter 23 M ,ppendi+ 0 D 0ortran 15 Ge'words
print statement performs output to screen
pointer attri(ute defined the varia(le as a pointer alias
private statement and
attri(ute
in a module
program construct start of a main program
pu0&ic statement and
attri(ute
in a module 6 visi(le outside
read statement performs input
rea& statement intrinsic data t'pe
recur$ive attri(ute allows functions and derived t'pe recursion
re$u&t attri(ute allows naming of function result
return statement returns from e+its su(routine or function
re3ind statement move read or write position to (eginning
$e&ect ca$e construct start of a case construct
$top statement terminate e+ecution of the main procedure
$u0routine construct start of a su(routine definition
target attri(ute allows a varia(le to ta)e a pointer alias
then construct part of if construct
type construct start of user defined t'pe
u$e statement (rings in a module
3here construct conditional assignment
3hi&e construct a while form of a do loop
3rite statement performs output
1E5
:hapter 23 K ,ppendi+ 0 D 0ortran 15 Ge'words
1EE
Index
,>%3,4.........................................................155p.
,ccessing ,rra' Elements.........................13, 105
,ccessing :omponents...................................12E
,:H,*3.4.................................................BC, 15E
,:=%384........................................................15E
,ctual arguments.............................................11<
,ddition.............................................................11
,dvance clause..................................................EC
,.I,3W4......................................................15B
,rgument .ntent...............................................11<
,rgument /assing............................................115
,rguments.......................................................11<
,rra' ;eclaration......................................11, 103
,%:....................................................................5
,%.!384.........................................................15E
,ssignment........................................................11
,T,!3J4.........................................................15E
>ase 10................................................................<
>ase 2..................................................................5
:all statement..................................................11<
:,%E statement................................................<E
:haos ame......................................................10
:haracter...........................................................13
:haracter constant.............................................1C
:haracter 9iterals..............................................1C
:haracter *epresentation....................................5
:I/9J3J,#4..................................................15B
:=II,!;R,*"IE!TR:="!T34........15C
:ompiler..............................................................<
:ompiler Error..................................................35
:ompiling............................................................C
:omple+ constant..............................................1C
:omple+ 9iterals...............................................1C
:omple+ num(er...............................................13
:omponent......................................................125
:omputer program..............................................2
:onditional :ontrolled 9ooping.......................51
:onditionall' :ontrolled 9oop E+ample..........E0
:onstant.............................................................1<
:ontains...........................................................11<
:=%384...........................................................15E
:ounter :ontrolled E+ample.............................5B
:ounter :ontrolled 9ooping.............................55
:/"RT.IE3T.IE4.........................................15C
:'cle statement.................................................5B
;,TER,!;RT.IE........................................15C
;ecimal !um(ers................................................<
;eclaration......................................................12E
;efinition........................................................125
;erived ;ata T'pes.........................................125
;irect access structure.......................................11
;iscriminant......................................................<3
;ivision.............................................................20
;o6loop..............................................................55
;'namic ,rra' ,llocation.........................13, 10<
;'namic ,rra' ;eclaration...............................12
;'namic ;eclaration.......................................10<
E6notation..........................................................1B
EAual to.............................................................31
Error Terminolog'.............................................35
Escape character..........................................1C, B5
E+it statement....................................................5B
E+ponentiation...................................................20
E+ternal............................................................113
E+ternal declaration.........................................11<
E+ternal *outines............................................11<
0ile =pen...........................................................C3
0ormal arguments............................................11<
0=*I,T statement..........................................E5
0unctions.........................................................115
ETR:=II,!;R,*"I!E!T3!"I>E*,
V,9"E, 9E!TH, %T,T"%4........................15C
!"plot..........................................................151
reater than.......................................................31
reater than or eAual.........................................31
.,:H,*3:4..............................................BC, 15E
.0 statement.......................................................<1
.0 THE! E9%E .0 statement............................<2
1EB
:hapter K .nde+
.0 THE! E9%E statement.................................<1
.I/9.:.T !=!E..............................................13
.mplicit t'ping...................................................13
.mplied do6loop.................................................1<
.nde+..................................................................11
.!T3,4.............................................................155
.nteger................................................................12
.nteger constants................................................1B
.nteger 9iterals..................................................1B
.ntent3in4..........................................................11<
.ntent3inout4.....................................................11<
.ntent3out4........................................................11<
.nterface (loc).................................................11<
.nternal.............................................................113
.nternal *outines.............................................11<
.ntrinsic 0unctions...........................................115
.rrational num(ers.............................................13
Ge'word....................................................12, 1E3
9E!RT*.I3%T*4.....................................BC, 15E
9E!3%T*4.................................................BC, 15E
9ess than............................................................31
9ess than or eAual..............................................31
9E3%T*1,%T*24...........................................15E
9T3%T*1,%T*24...........................................15E
9iterals...............................................................1B
99E3%T*1,%T*24...........................................15E
99T3%T*1,%T*24............................................15E
9=384..........................................................15E
9ogic Error........................................................3B
9ogical...............................................................13
9ogical constant................................................1C
9ogical :onstants..............................................1C
9ogical =perators..............................................<0
9oop..................................................................55
Iagic %Auare...................................................111
I,J9=:3,14................................................15B
I,JV,93,14................................................15B
I.!9=:3,14..................................................15B
I.!V,93,14..................................................15B
I=;3*1,*24................................................155p.
Iodule file......................................................1<1
Iodules...........................................................131
Ionte :arlo.....................................................10E
Iultidimensional ,rra's.................................103
Iultiplication....................................................20
!.!T3J4..........................................................155
!ot eAual to.......................................................31
=(Fect file........................................................1<1
=perands............................................................31
=perating %'stem................................................2
/arameter...........................................................1<
/i estimation....................................................10B
/recedence of =perations..................................21
/rogram 9a'out...............................................113
/rogram %tatement..............................................B
/'thagorean theorem.......................................10E
?uadratic eAuation............................................<3
*andomRnum(er34...........................................151
*andomRseed34................................................151
*ational num(ers...............................................13
*ead statement..................................................2C
*eal constants....................................................1B
*eal 9iterals......................................................1B
*eal num(er2....................................................13
*E,93,4.........................................................15B
*elational e+pression........................................31
*elational E+pressions......................................31
*elational =peration..........................................31
*elational =perator...........................................31
*elational =perator 3alternate4..........................31
*un6time Error..................................................3E
%econdar' source file......................................131
%E9E:T :,%E %tatement................................<E
%elector lists......................................................<B
%ide Effects......................................................11E
%ide6effect........................................................11E
%.!384............................................................15E
%ingle ;imension ,rra's..................................11
%ource file............................................................C
%?*T384.........................................................15E
%tatic ,rra' ;eclaration....................................12
%tatic ;eclaration......................................11, 10<
%tring.................................................................2B
%tring5...............................................................13
%u(program T'pes...........................................113
%u(programs....................................................113
%u(routines......................................................11E
%u(script............................................................11
%u(traction........................................................11
%"I3,14.........................................................15B
T,!3J4...........................................................15E
T*.I3%T*4...............................................BC, 15E
T'pe declaration................................................1<
"nit num(er.......................................................C3
1EC
:hapter M .nde+
"se %tatement..................................................1<0
"ser6;efined 0unctions...................................115
"sing 0unctions and %u(routines....................11<
Varia(le %cope.................................................11<
8hole num(er...................................................12
8rite statement..................................................2B
.and....................................................................<0
.eA......................................................................31
.ge......................................................................31
.gt.......................................................................31
.le.......................................................................31
.lt........................................................................31
.ne......................................................................31
.not.....................................................................<0
.or.......................................................................<0
5U........................................................................31
Z.........................................................................31
ZU......................................................................31
UU......................................................................31
[.........................................................................31
[U......................................................................31
1E1