Introduction To Programming Using Fortran 95
Introduction To Programming Using Fortran 95
Programming
using
Fortran 95
Ed Jorgensen
January, 2014
Version 2.0
Cover Diagram
The cover image is the plotted output from the chaos game program from chapter 11.
The image was plotted with GNUplot.
Copyright
Ed Jorgensen, 201, 201!
"ou are free#
to $hare % to cop&, distri'ute and transmit the wor(
to )emi* % to adapt the wor(
Under the following conditions#
+ttri'ution. "ou must attri'ute the wor( to ,-ntroduction to .rogramming using /ortran
012 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.
/or 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'&6sa5.05
+n& of the a'ove conditions can 'e waived if &ou get permission from the cop&right holder.
Nothing 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 /ortran......................................................................................................................................... 1
1. :omplete /ortran 01 ;ocumentation.......................................................................................... 1
1.! 8hat -s + .rogram...................................................................................................................... 2
1.1 <perating $&stem........................................................................................................................ 2
2 Computer Organiation.................................................................................................................... !
2.1 +rchitecture <verview................................................................................................................
2.2 :ompiler...................................................................................................................................... !
2. -nformation )epresentation......................................................................................................... !
2..1 ;ecimal Num'ers................................................................................................................ !
2..2 =inar& Num'ers................................................................................................................... 1
2.. :haracter )epresentation..................................................................................................... 1
2.! E*ercises...................................................................................................................................... 1
2.!.1 >ui? >uestions..................................................................................................................... 1
! "etting #tarted.................................................................................................................................. $
.1 )e@uired $(ills............................................................................................................................ A
.2 .rogram /ormats......................................................................................................................... A
.2.1 .rogram $tatement............................................................................................................... A
.2.2 :omments............................................................................................................................ A
.2. $imple <utput...................................................................................................................... B
.2.! E*ample C /irst .rogram..................................................................................................... B
. Te*t Editor................................................................................................................................... B
.! :ompiling.................................................................................................................................... B
.1 E*ecuting..................................................................................................................................... 0
.D E*ercises.................................................................................................................................... 10
.D.1 >ui? >uestions................................................................................................................... 10
.D.2 $uggested .roEects............................................................................................................. 10
4 %ortran &' ( )asic E*ements.......................................................................................................... 11
!.1 Faria'les.................................................................................................................................... 11
!.1.1 Faria'le Names.................................................................................................................. 11
!.1.2 Ge&words........................................................................................................................... 12
!.2 ;ata T&pes................................................................................................................................. 12
!.2.1 -nteger................................................................................................................................ 12
!.2.2 )eal.................................................................................................................................... 1
!.2. :omple*............................................................................................................................. 1
!.2.! :haracter............................................................................................................................ 1
!.2.1 9ogical............................................................................................................................... 1
!.2.D Historical ;ata T&ping....................................................................................................... 1
iii
!. ;eclarations............................................................................................................................... 1!
!..1 ;eclaring Faria'les............................................................................................................ 1!
!..2 Faria'le )anges................................................................................................................. 1!
!.. T&pe :hec(ing................................................................................................................... 1!
!..! -nitiali?ation....................................................................................................................... 11
!..1 :onstants........................................................................................................................... 11
!.! :omments.................................................................................................................................. 11
!.1 :ontinuation 9ines.................................................................................................................... 11
!.1.1 E*ample............................................................................................................................. 1D
!.D ;eclarations, E*tended $i?e Faria'les...................................................................................... 1D
!.D.1 -ntegers.............................................................................................................................. 1D
!.D.2 )eal.................................................................................................................................... 1A
!.A E*ercises.................................................................................................................................... 1A
!.A.1 >ui? >uestions................................................................................................................... 1A
!.A.2 $uggested .roEects............................................................................................................. 1B
' E+pressions...................................................................................................................................... 1&
1.1 9iterals....................................................................................................................................... 10
1.1.1 -nteger 9iterals................................................................................................................... 10
1.1.2 )eal 9iterals....................................................................................................................... 10
1.1.2.1 E6Notation.................................................................................................................. 10
1.1. :omple* 9iterals............................................................................................................... 20
1.1.! :haracter 9iterals............................................................................................................... 20
1.1.1 9ogical :onstants.............................................................................................................. 21
1.2 +rithmetic <perations............................................................................................................... 21
1.2.1 +ssignment........................................................................................................................ 21
1.2.2 +ddition............................................................................................................................. 21
1.2. $u'traction......................................................................................................................... 22
1.2.! Iultiplication.................................................................................................................... 22
1.2.1 ;ivision............................................................................................................................. 22
1.2.D E*ponentiation................................................................................................................... 2
1. <rder of <perations................................................................................................................... 2
1.! -ntrinsic /unctions..................................................................................................................... 2!
1.!.1 Iathematical -ntrinsic /unctions...................................................................................... 2!
1.!.2 :onversion /unctions........................................................................................................ 2!
1.!. $ummar&............................................................................................................................ 21
1.1 Ii*ed Iode.............................................................................................................................. 21
1.D E*amples................................................................................................................................... 2D
1.A E*ercises.................................................................................................................................... 2D
1.A.1 >ui? >uestions................................................................................................................... 2D
1.A.2 $uggested .roEects............................................................................................................. 2A
, #imp*e Input and Output............................................................................................................... 2&
D.1 <utput C 8rite........................................................................................................................... 20
D.1.1 <utput C .rint.................................................................................................................... 0
D.2 -nput C )ead.............................................................................................................................. 0
D. E*ample..................................................................................................................................... 1
iv
D.! E*ercises.................................................................................................................................... 2
D.!.1 >ui? >uestions................................................................................................................... 2
D.!.2 $uggested .roEects............................................................................................................. 2
$ -rogram Deve*opment.................................................................................................................... !'
A.1 Understand the .ro'lem............................................................................................................ 1
A.2 :reate the +lgorithm................................................................................................................. D
A. ;evelop the .rogram................................................................................................................. D
A.! Test5;e'ug the .rogram............................................................................................................ A
A.!.1 Error Terminolog&............................................................................................................. A
A.!.1.1 :ompiler Error........................................................................................................... A
A.!.1.2 )un6time Error........................................................................................................... B
A.!.1. 9ogic Error................................................................................................................. 0
A.1 E*ercises.................................................................................................................................... 0
A.1.1 >ui? >uestions................................................................................................................... 0
A.1.2 $uggested .roEects............................................................................................................. !0
. #e*ection #tatements....................................................................................................................... 41
B.1 )elational E*pressions.............................................................................................................. !1
B.2 9ogical <perators...................................................................................................................... !2
B. -/ $tatements............................................................................................................................. !2
B..1 -/ THEN $tatement........................................................................................................... !
B..1.1 -/ THEN $tatement, $imple /orm............................................................................ !
B..2 -/ THEN E9$E $tatement................................................................................................. !
B.. -/ THEN E9$E -/ $tatement............................................................................................ !!
B.! E*ample <ne............................................................................................................................. !1
B.!.1 Understand the .ro'lem.................................................................................................... !1
B.!.2 :reate the +lgorithm.......................................................................................................... !D
B.!. ;evelop the .rogram......................................................................................................... !A
B.!.! Test5;e'ug the .rogram.................................................................................................... !B
B.1 $E9E:T :+$E $tatement........................................................................................................ !0
B.D E*ample Two............................................................................................................................. 11
B.D.1 Understand the .ro'lem.................................................................................................... 11
B.D.2 :reate the +lgorithm.......................................................................................................... 11
B.D. ;evelop the .rogram......................................................................................................... 12
B.D.! Test5;e'ug the .rogram.................................................................................................... 12
B.A E*ercises.................................................................................................................................... 1
B.A.1 >ui? >uestions................................................................................................................... 1
B.A.2 $uggested .roEects............................................................................................................. 1!
& /ooping............................................................................................................................................ '$
0.1 :ounter :ontrolled 9ooping..................................................................................................... 1A
0.2 EJ-T and :":9E $tatements................................................................................................... 10
0. :ounter :ontrolled E*ample..................................................................................................... 10
0..1 Understand the .ro'lem.................................................................................................... D0
0..2 :reate the +lgorithm.......................................................................................................... D0
0.. ;evelop the .rogram......................................................................................................... D0
v
0..! Test5;e'ug the .rogram.................................................................................................... D1
0.! :onditional :ontrolled 9ooping............................................................................................... D1
0.1 :onditionall& :ontrolled 9oop E*ample.................................................................................. D
0.1.1 Understand the .ro'lem.................................................................................................... D
0.1.2 :reate the +lgorithm.......................................................................................................... D
0.1. ;evelop the .rogram......................................................................................................... D!
0.1.! Test5;e'ug the .rogram.................................................................................................... D1
0.D E*ercises.................................................................................................................................... D1
0.D.1 >ui? >uestions................................................................................................................... D1
0.D.2 $uggested .roEects............................................................................................................. DD
10 %ormatted Input0Output.............................................................................................................. ,&
10.1 /ormat..................................................................................................................................... D0
10.2 /ormat $pecifiers.................................................................................................................... D0
10. -nteger /ormat $pecifier.......................................................................................................... A0
10.! )eal /ormat $pecifier.............................................................................................................. A1
10.1 9ogical /ormat $pecifier......................................................................................................... A1
10.D :haracter /ormat $pecifier..................................................................................................... A2
10.A +dvance :lause....................................................................................................................... A
10.B E*ample................................................................................................................................... A
10.B.1 Understand the .ro'lem.................................................................................................. A!
10.B.2 :reate the +lgorithm........................................................................................................ A!
10.B. ;evelop the .rogram....................................................................................................... A!
10.B.! Test5;e'ug the .rogram.................................................................................................. AD
10.0 E*ercises.................................................................................................................................. AA
10.0.1 >ui? >uestions................................................................................................................. AA
10.0.2 $uggested .roEects........................................................................................................... AA
11 Characters and #trings................................................................................................................. $&
11.1 :haracter and $tring :onstants............................................................................................... A0
11.2 :haracter Faria'le ;eclaration................................................................................................ B0
11. :haracter Faria'le -nitiali?ation.............................................................................................. B0
11.! :haracter :onstants................................................................................................................. B0
11.1 :haracter +ssignment.............................................................................................................. B1
11.D :haracter <perators................................................................................................................. B1
11.A :haracter $u'strings................................................................................................................ B1
11.B :haracter :omparisons........................................................................................................... B2
11.0 -ntrinsic :haracter <perations................................................................................................. B2
11.10 E*ample................................................................................................................................. B
11.10.1 Understand the .ro'lem................................................................................................. B
11.10.2 :reate the +lgorithm...................................................................................................... B
11.10. ;evelop the .rogram..................................................................................................... B!
11.10.! Test5;e'ug the .rogram................................................................................................ B1
11.11 E*ercises................................................................................................................................ B1
11.11.1 >ui? >uestions............................................................................................................... B1
11.11.2 $uggested .roEects......................................................................................................... BD
vi
12 %i*e Operations.............................................................................................................................. .$
12.1 /ile <pen................................................................................................................................. BA
12.2 /ile 8rite................................................................................................................................. BB
12. /ile )ead.................................................................................................................................. BB
12.! )ewind..................................................................................................................................... B0
12.1 =ac(space................................................................................................................................ B0
12.D :lose /ile................................................................................................................................. 00
12.A E*ample................................................................................................................................... 00
12.A.1 Understand the .ro'lem.................................................................................................. 00
12.A.2 :reate the +lgorithm........................................................................................................ 00
12.A. ;evelop the .rogram....................................................................................................... 01
12.A.! Test5;e'ug the .rogram.................................................................................................. 02
12.B E*ercises.................................................................................................................................. 02
12.B.1 >ui? >uestions................................................................................................................. 0
12.B.2 $uggested .roEects........................................................................................................... 0
1! #ing*e Dimension 1rrays.............................................................................................................. &'
1.1 +rra& ;eclaration.................................................................................................................... 01
1.1.1 $tatic ;eclaration............................................................................................................. 01
1.1.2 $tatic +rra& ;eclaration.................................................................................................. 0D
1.1. ;&namic +rra& ;eclaration............................................................................................. 0D
1.1..1 ;&namic +rra& +llocation....................................................................................... 0A
1.2 +ccessing +rra& Elements....................................................................................................... 0A
1. -mplied ;o69oop..................................................................................................................... 0B
1.! -nitiali?ing +rra&s.................................................................................................................... 0B
1.1 E*ample................................................................................................................................... 00
1.1.1 Understand the .ro'lem.................................................................................................. 00
1.1.2 :reate the +lgorithm........................................................................................................ 00
1.1. ;evelop the .rogram..................................................................................................... 101
1.1.! Test5;e'ug the .rogram................................................................................................ 10
1.D +rra&s of $trings.................................................................................................................... 10
1.A E*ercises................................................................................................................................ 10!
1.A.1 >ui? >uestions............................................................................................................... 10!
1.A.2 $uggested .roEects......................................................................................................... 101
14 2u*tidimensiona* 1rrays............................................................................................................ 10$
1!.1 +rra& ;eclaration.................................................................................................................. 10A
1!.1.1 $tatic ;eclaration........................................................................................................... 10B
1!.1.2 ;&namic ;eclaration..................................................................................................... 10B
1!.1. ;&namic +rra& +llocation............................................................................................. 10B
1!.2 +ccessing +rra& Elements..................................................................................................... 100
1!. E*ample................................................................................................................................. 110
1!..1 Understand the .ro'lem................................................................................................. 110
1!..2 :reate the +lgorithm...................................................................................................... 111
1!.. ;evelop the .rogram..................................................................................................... 112
1!..! Test5;e'ug the .rogram................................................................................................ 11
1!.! E*ercises................................................................................................................................ 11!
vii
1!.!.1 >ui? >uestions............................................................................................................... 11!
1!.!.2 $uggested .roEects......................................................................................................... 11!
1' #u3programs................................................................................................................................ 11$
11.1 $u'program T&pes................................................................................................................. 11A
11.2 .rogram 9a&out..................................................................................................................... 11A
11.2.1 -nternal )outines............................................................................................................ 11B
11.2.2 E*ternal )outines........................................................................................................... 11B
11. +rguments.............................................................................................................................. 11B
11..1 +rgument -ntent............................................................................................................. 11B
11.! Faria'le $cope....................................................................................................................... 11B
11.1 Using /unctions and $u'routines.......................................................................................... 11B
11.1.1 +rgument .assing.......................................................................................................... 110
11.D /unctions............................................................................................................................... 110
11.D.1 -ntrinsic /unctions......................................................................................................... 110
11.D.2 User6;efined /unctions................................................................................................. 120
11.D.2.1 $ide Effects............................................................................................................ 120
11.A $u'routines............................................................................................................................ 120
11.B E*ample................................................................................................................................. 122
11.B.1 Understand the .ro'lem................................................................................................ 12
11.B.2 :reate the +lgorithm...................................................................................................... 12!
11.B. ;evelop the .rogram..................................................................................................... 121
11.B.! Test5;e'ug the .rogram................................................................................................ 12D
11.0 E*ercises................................................................................................................................ 12D
11.0.1 >ui? >uestions............................................................................................................... 12D
11.0.2 $uggested .roEects......................................................................................................... 12B
1, Derived Data 4ypes..................................................................................................................... 1!1
1D.1 ;efinition............................................................................................................................... 11
1D.2 ;eclaration............................................................................................................................ 12
1D. +ccessing :omponents.......................................................................................................... 12
1D.! E*ample <ne......................................................................................................................... 1
1D.!.1 Understand the .ro'lem................................................................................................ 1
1D.!.2 :reate the +lgorithm...................................................................................................... 1!
1D.!. ;evelop the .rogram..................................................................................................... 1!
1D.!.! Test5;e'ug the .rogram................................................................................................ 1A
1D.1 +rra&s of ;erived ;ata.......................................................................................................... 1A
1D.D E*ample Two......................................................................................................................... 1B
1D.D.1 Understand the .ro'lem................................................................................................ 1B
1D.D.2 :reate the +lgorithm...................................................................................................... 10
1D.D. ;evelop the .rogram..................................................................................................... 1!0
1D.D.! Test5;e'ug the .rogram................................................................................................ 1!2
1D.A E*ercises................................................................................................................................ 1!
1D.A.1 >ui? >uestions............................................................................................................... 1!
1D.A.2 $uggested .roEects......................................................................................................... 1!
1$ 2odu*es........................................................................................................................................ 14'
viii
1A.1 Iodule ;eclaration............................................................................................................... 1!1
1A.2 Use $tatement........................................................................................................................ 1!D
1A. Updated :ompilation :ommands......................................................................................... 1!D
1A.! Iodule E*ample .rogram..................................................................................................... 1!A
1A.!.1 Understand the .ro'lem................................................................................................ 1!A
1A.!.2 :reate the +lgorithm...................................................................................................... 1!B
1A.!. ;evelop the .rogram..................................................................................................... 1!B
1A.!..1 Iain .rogram........................................................................................................ 1!B
1A.!..2 Iodule )outines.................................................................................................... 1!0
1A.!.! :ompile the .rogram..................................................................................................... 110
1A.!.1 Test5;e'ug the .rogram................................................................................................ 110
1A.1 E*ercises................................................................................................................................ 111
1A.1.1 >ui? >uestions............................................................................................................... 111
1A.1.2 $uggested .roEects......................................................................................................... 111
1. 5ecursion..................................................................................................................................... 1'!
1B.1 )ecursive $u'routines........................................................................................................... 11
1B.2 )ecursive .rint =inar& E*ample........................................................................................... 11!
1B.2.1 Understand the .ro'lem................................................................................................ 11!
1B.2.2 :reate the +lgorithm...................................................................................................... 11!
1B.2. ;evelop the .rogram..................................................................................................... 111
1B.2.! Test5;e'ug the .rogram................................................................................................ 11D
1B. )ecursive /unctions.............................................................................................................. 11D
1B.! )ecursive /actorial E*ample................................................................................................. 11D
1B.!.1 Understand the .ro'lem................................................................................................ 11A
1B.!.2 :reate the +lgorithm...................................................................................................... 11A
1B.!. ;evelop the .rogram..................................................................................................... 11A
1B.!.! Test5;e'ug the .rogram................................................................................................ 11B
1B.1 )ecursive /actorial /unction :all Tree................................................................................. 110
1B.D E*ercises................................................................................................................................ 1D0
1B.D.1 >ui? >uestions............................................................................................................... 1D0
1B.D.2 $uggested .roEects......................................................................................................... 1D0
1& Character #tring 0 6umeric Conversions................................................................................. 1,!
10.1 :haracter $tring to Numeric :onversion.............................................................................. 1D
10.2 Numeric to :haracter $tring :onversion.............................................................................. 1D1
10. E*ercises................................................................................................................................ 1DD
10..1 >ui? >uestions............................................................................................................... 1DD
10..2 $uggested .roEects......................................................................................................... 1DA
20 #ystem #ervices........................................................................................................................... 1,&
20.1 ;ate and Time....................................................................................................................... 1D0
20.1.1 ;ate and Time <ptions.................................................................................................. 1D0
20.1.2 ;ate and Time E*ample .rogram.................................................................................. 1A0
20.2 :ommand 9ine +rguments.................................................................................................... 1A2
20.2.1 +rgument :ount............................................................................................................. 1A
20.2.2 Get +rguments............................................................................................................... 1A
i*
20.2. :ommand 9ine +rguments, E*ample .rogram............................................................. 1A!
20. E*ercises................................................................................................................................ 1AA
20..1 >ui? >uestions............................................................................................................... 1AA
20..2 $uggested .roEects......................................................................................................... 1AA
21 1ppendi+ 1 ( 1#CII 4a3*e.......................................................................................................... 1$&
22 1ppendi+ ) ( 7indo8s #tart9:p Instructions......................................................................... 1.1
22.1 8or(ing /iles........................................................................................................................ 1B1
22.2 <'taining The :ompiler........................................................................................................ 1B1
22. :ommand .rompt.................................................................................................................. 1B2
22..1 8indows J.5Fista5A...................................................................................................... 1B2
22..2 8indows B..................................................................................................................... 1B2
22.. :ommand .rompt 8indow........................................................................................... 1B2
22..! ;evice and ;irector&..................................................................................................... 1B2
22.! :ompiler -nstallation Ferification......................................................................................... 1B
22.1 :ompilation........................................................................................................................... 1B
22.D E*ecuting............................................................................................................................... 1B
22.A E*ample................................................................................................................................. 1B!
2! 1ppendi+ C ( 5andom 6um3er "eneration............................................................................ 1.'
2.1 -nitiali?ation........................................................................................................................... 1B1
2.2 Generating )andom Num'er................................................................................................. 1B1
2. E*ample................................................................................................................................. 1BD
2.! E*ample................................................................................................................................. 1BA
24 1ppendi+ D ( Intrinsic %unctions.............................................................................................. 1.&
2!.1 :onversion /unctions............................................................................................................ 1B0
2!.2 -nteger /unctions................................................................................................................... 1B0
2!. )eal /unctions....................................................................................................................... 100
2!.! :haracter /unctions............................................................................................................... 100
2!.1 :omple* /unctions................................................................................................................ 101
2!.D +rra& /unctions..................................................................................................................... 101
2!.A $&stem -nformation /unctions.............................................................................................. 102
2' 1ppendi+ E ( Visua*iation 8ith "6:p*ot............................................................................... 1&!
21.1 <'taining GNUplot............................................................................................................... 10
21.2 /ormatting .lot /iles............................................................................................................. 10
21.2.1 Header............................................................................................................................ 10!
21.2.2 /ooter............................................................................................................................. 10!
21. .lotting /iles.......................................................................................................................... 10!
21.! E*ample................................................................................................................................. 10!
21.!.1 .lot .rogram.................................................................................................................. 101
21.!.2 .lot /ile.......................................................................................................................... 10D
21.!. .lot <utput..................................................................................................................... 10D
2, 1ppendi+ % ( ;ui ;uestion 1ns8ers....................................................................................... 1&$
2D.1 >ui? >uestion +nswers, :hapter 1....................................................................................... 10A
*
2D.2 >ui? >uestion +nswers, :hapter 2....................................................................................... 10A
2D. >ui? >uestion +nswers, :hapter ....................................................................................... 10A
2D.! >ui? >uestion +nswers, :hapter !....................................................................................... 10B
2D.1 >ui? >uestion +nswers, :hapter 1....................................................................................... 10B
2D.D >ui? >uestion +nswers, :hapter D....................................................................................... 100
2D.A >ui? >uestion +nswers, :hapter A....................................................................................... 100
2D.B >ui? >uestion +nswers, :hapter B....................................................................................... 100
2D.0 >ui? >uestion +nswers, :hapter 0....................................................................................... 200
2D.10 >ui? >uestion +nswers, :hapter 10................................................................................... 201
2D.11 >ui? >uestion +nswers, :hapter 11.................................................................................... 202
2D.12 >ui? >uestion +nswers, :hapter 12................................................................................... 202
2D.1 >ui? >uestion +nswers, :hapter 1................................................................................... 20
2D.1! >ui? >uestion +nswers, :hapter 1!................................................................................... 20!
2D.11 >ui? >uestion +nswers, :hapter 11................................................................................... 20!
2D.1D >ui? >uestion +nswers, :hapter 1D................................................................................... 201
2D.1A >ui? >uestion +nswers, :hapter 1A................................................................................... 20D
2D.1B >ui? >uestion +nswers, :hapter 1B................................................................................... 20D
2D.10 >ui? >uestion +nswers, :hapter 10................................................................................... 20B
2D.20 >ui? >uestion +nswers, :hapter 20................................................................................... 20B
2$ 1ppendi+ " ( %ortran &' <ey8ords......................................................................................... 20&
Inde+................................................................................................................................................... 21!
Illustration Index
-llustration 1# :omputer +rchitecture........................................................................................................
-llustration 2# /ortran 01 :ompile .rocess................................................................................................!
-llustration # /actorial )ecursion Tree.................................................................................................110
*i
*ii
1 Introduction
:omputers are ever&where in our dail& lives. =etween 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 /ortran 01
programming language. This introduction is geared for non6computer science maEors. +s such, this
te*t is not a complete, comprehensive guide to the /ortran 01 programming language. The primar&
focus is on an introduction to pro'lem solving and algorithm development. +s such, man& details of
the /ortran 01 language are omitted.
1.1 Why Learn Programming
/or science and technical maEors, computers are used e*tensivel& in all aspects of ever& 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 is developed, and 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.
Unfortunatel&, learning programing and how a computer reall& wor(s ma& ruin some = movies.
1. Fortran
/ortran is a programming language often used '& the scientific communit&. -ts name is a contraction of
/<)mula T)+Nslation. /<)T)+N is one of the earliest programming languages.
This te*t utili?es the /ortran 00501 standard. <lder versions of /ortran, li(e /ortran AA, are not
referenced. The older /ortran versions have less features and re@uire additional, often 'urdensome,
formatting re@uirements.
1.! Com"lete Fortran 95 #ocumentation
This te*t it is not a comprehensive or complete reference to the /ortran 01 language. The entire GNU
/ortran 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. :onse@uentl&, 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:.U, 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 UN-J59inu*. .rograms written in /ortran 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 Unit 3:.U4, )andom +ccess
Iemor& 3)+I4, .rimar& $torage, and -nput5<utput devices 3i.e., screen, (e&'oard, and mouse4, and
an interconnection referred to as =U$. The primar& storage ma& 'e a $olid $tate ;rive 3$$;4, dis(
drive, or other t&pe of primar& storage media.
+ 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 :.U 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.
10
2
10
1
10
0
1000 100 10 1
1 2 !
8hich means,
12! = 11000 2100 10 !1
12! = 110
210
2
10
1
!10
0
The decimal s&stem is base 10 using the digits 0 through 0.
!
Illustration 2: Fortran 95 Compile Process
%ortran &' !om(i)er *+ecutab)e
Program %i)e
:hapter 2 M :omputer <rgani?ation
2.3.2 Binary Numbers
+ 'it is the 'asic unit of information in computing and digital communications. + 'it can have onl&
one of two values, 0 or 1. The term 'it is a contraction of 'inar& digit.
The 'inar& s&stem, as well as its math, operates in base 2, using two s&m'ols, 0 and 1.
2
A
2
D
2
1
2
!
2
2
2
2
1
2
0
12B D! 2 1D B ! 2 1
0 0 0 0 1 1 0 1
-n 'ase 2, we put the digits 0 or 1 in columns 2
0
, 2
1
, 2
12
2
02
1
12
0
= B!1
8hich is decimal is 1
10
.
+ set of B 'its is a referred to as a '&te. :omputer data is t&picall& allocated in '&tes or sets of '&tes.
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 @ui? @uestions 'ased on this chapter.
2.4.1 Quiz Questions
=elow are some @ui? @uestions.
14 How is information represented in the computerN
24 8hat does the /ortran compiler doN
4 8hat architecture component connects the memor& to the :.UN
!4 8hat are the following 'inar& values in decimalN
a4 0000101
2
'4 0001001
2
c4 0001101
2
d4 0010101
2
14 How are characters represented in the computerN
1
:hapter 2 K :omputer <rgani?ation
D4 8here are programs stored when the computer is turned offN
A4 8here must programs 'e located when the& are e*ecutingN
D
! -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 hierarchical computer director& structure
/ile manipulation 3create, delete, rename, move, etc.4
Usage of the command prompt 38indows4 or terminal interface 3Uni*, I+:4
+'ilit& to edit a te*t file
-ncludes selecting and learning a te*t editor 3i.e., Notepad, NotepadOO, emacs, etc.4
-f &ou are unsure a'out an& of these re@uirements &ou will need to learn them 'efore continuing.
/ortunatel&, the& are not difficult. +dditionall&, there are numerous tutorials availa'le on the 8e'.
The following sections assume that the /ortran 01 compiler is installed and availa'le. /or additional
information regarding o'taining and installing the compiler, refer to +ppendi* =. The /ortran 01
compiler is availa'le for download at no cost.
!. Program Formats
/ortran 01 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
+ /ortran 01 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. /or e*ample,
comments t&picall& include information a'out the program. /or programming assignments, the
comments should include the programmer name, assignment num'er, and a 'rief description of the
program.
A
:hapter K Getting $tarted
3.2.3 imple !utput
+ program can displa& a simple message to the screen '& using the "rite statement. /or 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 re@uirements.
! 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 a user created
wor(ing director&. /or this e*ample, a wor(ing director& named 7fortran7 was created and the file
created and edited in that location.
+ file name is t&picall& comprised of two partsP a name and an e*tension. -n this e*ample, the file
name is hw and the e*tension is .f95. The usual e*tension for this and future programs will 'e .f95
which indicates that the file is a /ortran 01 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 adEusted for the compiler and e*ecute steps in the following
sections.
!.$ Com"iling
<nce the program is t&ped into a file, the file must 'e compiled. :ompiling will convert the human
reada'le /ortran program, or source file, into a computer reada'le version 3in 'inar&4.
-n order to compile, the command prompt 38indows4 or terminal interface 3Uni*, I+:4 is re@uired.
This interface will allow commands to 'e t&ped directl& into the computer 3instead of using a mouse4.
<nce started, it is t&picall& necessar& to change directories 3from the default location4 to the location of
where the hw.f95 source file was located 3form the previous steps4. :hanging directories is t&picall&
done with a cd <directoryName> command. /or e*ample, cd fortran 3which is the name of the
director& used in this e*ample4. The prompt t&picall& changes to include the current director& location.
B
:hapter M Getting $tarted
-n the e*ample '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#
C:\fortran> gfortran -o hw hw.f95
This command will tell the 7g=ortran7 compiler to read the file hw.f95 and, if there are no errors,
create an e*ecuta'le file. <n 8indows 'ased machines the e*ecuta'le file is named hw.exe. +nd on
Uni* or Iac 'ased machines, the e*ecuta'le is named hw 3no e*tension4. -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 on a 8indows 'ased machine, t&pe the name of the e*ecuta'le file. /or
e*ample, to e*ecute or run the hw.exe program#
C:\fortran> hw
Hello World
C:\fortran>
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
:hapter K Getting $tarted
To e*ecute or run a program on a Uni* or I+: 'ased machine, t&pe ,.52 and the name of the
e*ecuta'le file. /or e*ample, to e*ecute or run the hw program#
c:\fortran> ./hw
Hello World
c:\fortran>
The output 37Hello 8orld7 as displa&ed on the screen4 will 'e the same for 8indows, Uni*, or I+:
'ased machines.
!.0 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
3.&.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat the the input file for the compilerN
24 8hat is the output file from the compilerN
4 /ortran program must start with and end with what statementN
!4 How are /ortran 01 comments mar(edN
14 8hat is the t&pical /ortran 01 source file e*tensionN
D4 8hat is the t&pical /ortran 01 compiler output file e*tension 3after the program is compiled4N
3.&.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 :reate a wor(ing director& for the storage of program files 3on the computer 'eing used4.
24 <'tain and install the GNU /ortran 01 compiler on a suita'le computer. )efer to +ppendi* =
as needed.
4 T&pe in the hello world program, compile, and e*ecute the program.
!4 Update 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
/ortran language. This section descri'es some of the 'asic elements of /ortran. +dditional
information will 'e added in later sections.
$.1 3ariables
The 'asic concept in a program is the concept of a varia'le. Faria'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. /ortran 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.
Faria'le Name Q !2
Faria'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 2 characters. :apital letters are treated the same wa& as
lower6case letters, 3i.e., ,+++2 is the same varia'le as ,aaa24.
/or 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!
Note 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 /ortran 01 C =asic Elements
4.1.2 *ey+or's
-n programming, a (e&word is a word or identifier that has a special /ortran meaning. /or 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 as varia'le names. That
is, a varia'le name of program or write is not allowed.
+s additional /ortran 01 statements and language constructs are e*plained, more (e&words will 'e
identified. -n general, words used for /ortran language statements, attri'utes, and constructs will li(el&
'e (e&words. + complete list of (e&words or reserved words is located in +ppendi* /.
$. #ata Ty"es
/ortran, li(e man& other high level programming languages, supports several different data t%pes to
ma(e data manipulation easier. The most fre@uentl& used data t&pes are integer and floating point.
<ther data t&pes are comple* num'ers, characters and logical data.
-n a /ortran statement, data can appear either as a literal 3e.g., an actual value such as .1!110, 1D,
61.!e6!4 or as a varia'le name which identifies a location in memor& to store the data.
The five 'asic /ortran 01 data t&pes are as follows#
4ype Description
integer Faria'le that is an integer or whole num'er 3not a
fraction4 that can 'e positive, negative, or ?ero.
rea* Faria'le that can set set to a real num'er.
comp*e+ Faria'le that can 'e set to a comple* num'er.
character Faria'le that is a character or se@uence of
characters.
*ogica* Faria'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, 621, and 1,1!B. -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. /or integer division, no
rounding will occur as the fractional part is truncated.
1 /or more information regarding integers, refer to# http#55en.wi(ipedia.org5wi(i5-nteger
12
:hapter ! M /ortran 01 C =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 num'ers with repeating decimals include T,
2 and e. +dditional e*amples
include 1.1, 1.0, and .1!110. /ortran 01 will accept 1. as 1.0. +ll e*amples in this te*t will include
the ,.02 to ensure clarit&.
4.2.3 Comple#
+ comple* num'er
is 32 Y 2 Y 24
which is B. The /ortran e*ponentiation operation is specified with a dou'le asteris(s 3BB4.
/or e*ample, to declare the varia'les, ans and 'alue1,
real :: ans, value1=2.0
and calculate the e*ponentiation,
ans = value1 ** 3
which will set the varia'le ans to B.0. The data t&pes of the varia'les, real in this e*ample, should 'e
the same.
5.! &rder of &"erations
/ortran follows the standard mathematical order of operations or precedence of operations. That is,
multiplication and division are performed 'efore addition and su'traction. /urther, 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 /ortran 01 precedence levels#
-recedence
/eve*
Operator Operation
1
st
9 unar& 6
2
nd
BB e*ponentiation
rd
B 0 multiplication and division
!
th
A 9 addition and su'traction
/or 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&. /or e*ample, declaring the varia'les ans1,
ans2, num1, num2, and num3.
integer :: ans1, ans2, num1=20, num2=50, num3=10
and calculating the ans1 and ans2, as follows#
ans1 = num1 + num2 * num3
ans2 = (num1 + num2) * num3
will set to ans1 to 120 and ans2 to A00 3'oth integers4.
2
:hapter 1 K E*pressions
5.$ Intrinsic Functions
-ntrinsic functions are standard 'uilt6in functions that are provided '& /ortran. 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 5athematical ,ntrinsic %unctions
The intrinsic or 'uilt6in functions include the standard mathematical functions such as sine, cosine,
tangent, and s@uare root.
/or e*ample, the cosine of > is 61.0. ;eclaring and initiali?ing the varia'les x and pi as follows,
real :: z
real, parameter :: pi = 3.14159
and then performing the calculation of the cosine the varia'le pi as follows,
z = cos(pi)
which will set z to 61.0. The varia'le pi is the input argument.
-.4.2 Con6ersion %unctions
<ther intrinsic functions include functions to change the t&pe of varia'les or values. The 'asic
conversion functions are as follows#
%unction E+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
/or e*ample, given the following varia'le declarations,
integer :: inum1=10, inum2, inum3
real :: rnum1, rnum2 = 4.8
and calculate the rnum1, inum2 and inum3,
rnum1 = real(inum1)
inum2 = int(rnum2)
inum3 = int(rnum3)
which will set to rnum1 to 10.0, inum2 to !, and inum3 to 1.
2!
:hapter 1 M E*pressions
-.4.3 ummary
+ summar& of some of the more common intrinsic functions include#
%unction Description
:<$384 )eturns real cosine of real argument 8 in radians.
-NT3+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.
N-NT3J4 )eturns the nearest integer to real value J 3thus rounding
up or down as appropriate4.
)E+93+4 :onverts integer argument + to real.
$-N384 )eturns real sine of real argument 8 in radians.
$>)T384 )eturns the real s@uare root of real argument 8P 8 must 'e
positive.
T+N3J4 )eturns the real tangent of real argument J in radians.
+ more complete list of intrinsic functions in located in +ppendi* ;.
5.5 6ixed 6ode
-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
+n& integers values are converted to real onl& when mi*ed6mode is encountered on the same operation
t&pe. :onversion ma& also occur on assignment.
Une*pected conversions can cause pro'lems when calculating values. -n order to avoid such pro'lems,
it is strongl& recommended to not use mi*ed6mode. There are a series of rules associated with mi*ed6
mode operations. -n some circumstances, these rules can 'e confusing. /or simplicit&, those rules are
not covered in this te*t.
-f it is necessar& to perform calculations with different data t&pes, such as integers and reals, the
intrinsic or 'uilt6in conversion functions should 'e used to ensure correct and predicta'le results. This
also allows the programming greater control of when t&pes are converted. -n ver& comple*
calculations, this would help ensure clarit& and address precision issues. /urther recommendations to
address highl& precise calculations are not addressed in this te*t.
21
:hapter 1 K E*pressions
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 findvelocity
! 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 (*,*)
! Calculate the velocity
velocity = acceleration * time
write (*,*) "Velocity = ", velocity
end program findvelocity
+dditional information regarding how to perform input and output in the ne*t chapter. The comments
are not re@uired, 'ut help ma(e the program easier to read and understand.
5.5 ,xercises
=elow are some @ui? @uestions and proEect suggestion 'ased on this chapter.
-.2.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat is the assignment operatorN
24 8hat is the e*ponentiation operatorN
4 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
14 8hat are the two logical constantsN
D4 9ist three intrinsic functions.
2D
:hapter 1 M E*pressions
A4 8rite the single /ortran statement for each of the following formulas. "ou ma& assume all
varia'les are alread& declared as real values. +dditionall&, &ou ma& assume the varia'le .- is
set as a parameter and initiali?ed to .1!110.
x1 =
(
,
)
(!a
2
+!b
2
+c
2
) c
x2 =
2a
c
cos( b) sin( b)
x3 =
b +
(b
2
4 a c)
2a
-.2.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 T&pe in the velocit& program, compile, and e*ecute the program. :hange the declared values,
compile, and e*ecute the modified program. Ferif& 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 ,e@uation of time2 which is:
b = 2 ( n .1) / !,4
e = &..$ sin(23) $.'! cos(b) 1.' sin(b)
8here, n is the da& num'er. /or 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 316D!4 from the user and an integer. The program
should perform the appropriate t&pe conversions, perform the re@uired calculations, and displa&
the n, b, and final e values. Test the program on a series of different values.
2A
:hapter 1 K E*pressions
2B
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. /or
e*ample#
write (*,*) "Hello World"
8hich will send the message, referred to as a string, Ce**o 7or*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 /ortran 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. /or e*ample, to declare the
varia'les num1, num2, and num3.
integer :: num1=20, num2=50, num3=10
the write statement to displa& num1 would 'e,
write (*,*) num1
The free format allows the /ortran 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. /or e*ample, using the
previous declarations,
write (*,*) "Number 1 = ", num1, "Number 2 = ", num2
The information inside the @uotes is displa&ed as is, including capitali?ation and an& spelling errors.
8hen the @uotes 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&.
20
:hapter D 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.
/or e*ample, using the previous declarations,
print *,"Number 1 = ", num1, "Number 2 = ", num2
The information inside the @uotes is displa&ed as is, including capitali?ation and an& spelling errors.
8hen the @uotes 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. /or 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 /ortran compiler to
determine the appropriate format for the information 'eing read.
Iultiple varia'les can 'e read with one write statement. /or 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 re@uired. 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 re@uested '& 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 re@uested.
/or e*ample, to read a date, a program might re@uest month, date, and &ear as three separate varia'les.
Given 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
0
:hapter D M $imple -nput and <utput
$ince the program is re@uesting 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 re@uested here is an integer, so integers should 'e entered. .roviding a real
num'er or character 3e.g., 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
1
:hapter D K $imple -nput and <utput
The comments are not re@uired, '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.
0.$ ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
&.4.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat does the (*,*) meanN
24 8hat is the statement to output a message ,.rogramming is /un\2
4 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 proEects.
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 re@uest a circle diameter. The formula for circler area must
'e adEusted accordingl&. )ecall that radius U diameter divided '& two. Test the program on
several sets of input.
4 T&pe in the velocit& program from the previous chapter and update to prompt for and re@uest
input for the acceleration and time, and then displa& the results. Test the program on several
sets of input.
!4 8rite a /ortran 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.
2
a
'
c
:hapter D M $imple -nput and <utput
14 8rite a /ortran program compute geometric information for a Gite. The program should read
the a, c and p lengths and compute the ! 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#
! = (a
2
p
2
4
) ( c
2
p
2
4
)
Test the program on several sets of input.
a
p
@
c
:hapter D K $imple -nput and <utput
!
5 Program #e)elo"ment
8riting or developing programs is easier when following a clear methodolog&. The main steps in the
methodolog& are#
Understand 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 7nderstand 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
re@uired and the applica'le input information. -n this e*ample, the formula for the period of a
pendulum is#
"eriod = 2
#
g
1 +
1
4
sin
2
(
$
2
)
8here#
g U 0B0 cm5sec
2
U .1!110
# 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. /or 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 # and $ then calculate and displa& the
original input and the period of the pendulum with the given length and angle of displacement.
1
9
]
:hapter A K .rogram ;evelopment
5. Create the %lgorithm
The algorithm is the name for the ordered se@uence 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.
/or this pro'lem, the varia'les and constants must 'e declared, the applica'le headers and prompts
displa&ed, and the values for # and $ read from the user. Then the period can 'e calculated 'ased on
the provided formula and the results displa&ed. /ormali?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 re@uire more e*tensive
algorithms. E*amples in later chapters will include more comple* programs. /or 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 (*,*)
D
:hapter A M .rogram ;evelopment
! prompt for and read the length and angle values
write (*,*) "Enter Length and Angle values:"
read (*,*) length, angle
! 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 re@uired, 'ut helps ma(e the program easier to read. Note 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.$ Test8#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. /or 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.
2.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.
2.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
A
:hapter A K .rogram ;evelopment
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. /or
e*ample, if the correct /ortran statement ,write 3Y,Y42 is entered incorrectl& as ,wrote 3Y,Y42, an error
will 'e generated.
-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, 1 in this e*ample, represents the line num'er where the error occurred. Using a te*t
editor that displa&s line num'ers, the statement that caused the error can 'e @uic(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 1B 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.
2.4.1.2 Run3time "rror
+ run6time error is something that causes the program to crash. /or e*ample, if the a num'er is
re@uested from the user and a letter is entered, that can cause occur.
/or 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
B
:hapter A M .rogram ;evelopment
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. Until then, proving
the correct data t&pe will avoid this (ind of error.
2.4.1.3 .ogic "rror
+ logic error is when the program e*ecutes, 'ut does not produce the correct result. /or e*ample,
coding a provided formula incorrectl& or attempting to computer the average of a series of num'ers
'efore calculating the sum.
/or 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
re@uired. 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. /urther
information will 'e provided in later chapters regarding advice on finding logic errors.
5.5 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
2.-.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat are the four program development stepsN
0
:hapter A K .rogram ;evelopment
24 8hat are the three t&pes of errorsN
4 -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.
2.-.2 uggeste' Pro(ects
=elow are some suggested proEects.
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 %ircle&rea
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
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 / !)r
!
Test the program using several different input values.
!0
9 '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.
/ortran -/ statements and5or :+$E statements are used to allow a program ma(es decisions.
9.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 or logical
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#
5e*ationa*
Operation
5e*ationa* Operator
Dnorma*E
5e*ationa* Operator
Da*ternateE
Greater than F .gt.
Greater than or
e@ual
F@ .ge.
9ess than G .*t.
9ess than or e@ual G@ .*e.
E@ual to @@ .eH.
Not e@ual to 0@ .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 ma& 'e re@uired to support older /ortran 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 e@ual signs4 is used to compare. The ,@2 3single e@ual4 is used for assignment 3setting
a varia'le4. The ,@@2 does not change an& values, while the ,@2 does.
/or e*ample, given the declaration of,
integer :: gameLives
it might 'e useful to (now if the current value of game#ives is greater than 0.
!1
:hapter B K $election $tatements
-n this case, the logical or relational e*pression would 'e,
(gamelives > 0)
8hich will result in a true or &alse result 'ased on the value of the varia'le gamelives.
9. Logical &"erators
9ogical operators are used 'etween two logical varia'les or two logical e*pressions. The& are#
/ogica* Operator E+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.
/or e*ample, given the declaration of,
integer :: gameLives, extraLives
it might 'e useful to (now if the current value of game#ives 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 +N; 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.
+ logical e*pression is a relational e*pression or a com'ination of relational e*pressions and logical
operators.
9.! IF 'tatements
-/ 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 -/
statement. Each of the forms is e*plained in the following sections.
!2
:hapter B M $election $tatements
7.3.1 ,% 0/"N tatement
The -/ statement, using the relational operators, is how programs ma(e decisions. The general format
for an -/ statement is as follows#
if ( <relational expression> ) then
<fortran statement(s)>
end if
8here the Zfortran statements[ ma& include one or more valid /ortran statements.
/or e*ample, given the declaration of,
integer :: gameLives
'ased on the current value of gamelives is, a reasona'le -/ statement might 'e#
if ( gameLives == 0 ) then
write (*,*) "Game Over."
write (*,*) "Please try again."
end if
8hich will displa& the message ,Game <ver2 if the value of gamelives is less than or e@ual to 0.
7.3.1.1 ,% 0/"N tatement8 imple %orm
+dditionall&, another form of the -/ 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 re@uired. However, onl& one statement can 'e e*ecuted.
7.3.2 ,% 0/"N "." tatement
The -/ THEN E9$E statement e*pands the 'asic -/ statement to also allow a series of statements to 'e
performed if the logical e*pression evaluates to &alse.
The general format for an -/ THEN 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 /ortran statements.
!
:hapter B K $election $tatements
/or e*ample, given the declaration of,
integer :: gameLives
'ased on the current value of game#ives is, a reasona'le -/ THEN 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 Going2 if the value of game#ives is greater than 0
and displa& the message ,E*tra 9ife Granted2 if the value of game#ives is less than 0.
7.3.3 ,% 0/"N "." ,% tatement
The -/ THEN E9$E -/ statement e*pands the 'asic -/ statement to also allow a series of -/ statements
to 'e performed in a series.
The general format for an -/ THEN E9$E -/ 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 /ortran statements.
/or e*ample, given the declaration of,
integer :: gameLives
'ased on the current value of game#ives is, a reasona'le -/ THEN E9$E -/ 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 Going2 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 Granted2 if the value of gamelives is e@ual to 0.
!!
:hapter B M $election $tatements
9.$ ,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#
Understand 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 @uadratic e@uation in the form#
a x
2
+ b x + c = 0
Each of the steps, as applied to this pro'lem will 'e reviewed.
7.4.1 9n'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 @uadratic e@uation is as follows#
x =
b
(b
2
4a c)
2a
-n the @uadratic e@uation, the term b
2
!a c is the discriminant of the e@uation. 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 @uadratic e@uation. These two
solutions represent the two possi'le answers. -f the e@uation 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 e@uation. -f the e@uation 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 e@uation. -f the e@uation solution is
graphed, the curve representing the solution will not cross the x6a*is and this no real num'er
solution. However, mathematicall& the s@uare 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. /or this pro'lem, it is appropriate to use
real values.
!1
:hapter B 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#
-ositive Discriminant Iero Discriminant 6egative Discriminant
Two real solutions <ne real solution Two comple* solutions
E*ample#
*
2
0*
E*ample#
2*
2
!*2
E*ample#
*
2
*
Two distinct x6intercepts <ne x6intercept No x6intercept
)oot 1 U 60.B2
)oot 2 U 62.D1B
)oot 1 U 61.0 )oot U 60.1 O 0.BDD
)oot U 60.1 6 0.BDD
The e*amples provided a'ove are included in the e*ample solution in the following sections.
7.4.2 Create the 4lgorithm
The algorithm is the name for the ordered se@uence of steps involved in solving the pro'lem. The
varia'les must 'e defined and an initial header displa&ed. /or this pro'lem, the a, b, and c values will
need to 'e read from the user. /ormali?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,
!D
: :
:
:hapter B M $election $tatements
! calculate and display root
! if discriminant is >0,
! calculate and display root1 and root2
! if discriminant is <0,
! calculate and display complex root1 and root2
/or convenience, the steps are written a program comments.
7.4.3 De6elop 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 and display 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 and 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
!A
:hapter B K $election $tatements
! if discriminant is <0,
! calculate and 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 a complex root:"
write(*,*) "root 1 = ", root1, "+i", root2
write(*,*) "root 2 = ", root1, "-i", root2
end if
end program quadratic
The indentation is not re@uired, 'ut does help ma(e the program easier to read.
7.4.4 0est:Debug 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 a complex root:
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 a complex root:
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.
!B
:hapter B M $election $tatements
9.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.
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 /ortran 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 statement3s46[, ..., Zfortran
statement3s46n[ and Zfortran statement3s46default[ are se@uences of one or more e*ecuta'le statements.
The selector61, selector62, selector6, ..., 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 e@ual to value61
The fourth form means all values that are less than or e@ual 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 se@uence of statements in Zfortran statement3s4[ are e*ecuted.
-f the result is not in an& one of the selectors, there are two possi'ilities#
!0
:hapter B K $election $tatements
if :+$E ;E/+U9T is there, then the se@uence of statements in statements6;E/+U9T are
e*ecuted, followed '& the statement following EN; $E9E:T
if the :+$E ;E/+U9T is not there, the statement following EN; $E9E:T is e*ecuted
The constants listed in selectors must 'e uni@ue. The :+$E ;E/+U9T is optional. =ut with a :+$E
;E/+U9T, &ou are guaranteed that whatever the selector value, one of the la'els will 'e used. The
place for :+$E ;E/+U9T can 'e an&where within a $E9E:T :+$E statementP however, putting it at
the end would 'e more natural.
/or 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 (13:23)
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. /or 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 (4,6,9,11)
daysinmonth = 30
10
:hapter B M $election $tatements
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 ade@uate if the range of the &ear is sufficientl& limited.
9.0 ,xam"le T*o
+ t&pical pro'lem is to assign grades 'ased on a t&pical grading standard.
7.&.1 9n'erstan' the Problem
/or this e*ample, the program will assign grades using the following grade scale#
+ = : ; /
+[U00 B0 6 B0 A0 6 A0 D0 6 D0 ZU10
The program will read three test scores, compute the average, and displa& the appropriate grade 'ased
on the average.
7.&.2 Create the 4lgorithm
The algorithm is the name for the ordered se@uence of steps involved in solving the pro'lem.
/or 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, test3
! integer -> testave
! display initial header
! read the test1, test2, and test3 values
Ne*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. /ormali?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
/or convenience, the steps are written a program comments.
11
:hapter B K $election $tatements
7.&.3 De6elop the Program
=ased on the algorithm, the following program can 'e created.
program grades
! declare variables
implicit none
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 re@uired, 'ut does help ma(e the program easier to read.
7.&.4 0est:Debug 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.
12
:hapter B M $election $tatements
-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.
9.5 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
7.2.1 Quiz Questions
=elow are some @ui? @uestions.
14 9ist the si* relational operatorsN
24 9ist the three 'asic logical operatorsN
4 /or each of the following, answer .true. or .=a*se. 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 .or. b2) .and. b3 ) ______________
( b1 .or. (b2 .and. b3) ) ______________
( .not. ( i < j ) ) ______________
( j < i ) ______________
!4 8rite the /ortran -/ THEN statements to displa& the message LGame <verL if the integer
varia'le lives is _ to 0. "ou ma& assume the varia'le lives is alread& declared as an integer
and initiali?ed.
1
:hapter B K $election $tatements
14 8rite the /ortran -/ THEN statements 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. "ou
ma& assume the varia'le num is alread& declared as an integer and initiali?ed.
D4 8rite the /ortran statements to compute the formula
z =
x
y
assuming the values for integer
varia'les x, y, and z are previousl& set. However, if y U 0, do not compute the formula, set z U
0, and displa& an error message, LW not calculatedL. "ou ma& assume the varia'les x, y, and z
are alread& declared as an integers and initiali?ed.
A4 8rite the statements re@uire to compute the following formula using real varia'les f, x, and y.
Use a single -/ THEN E9$E -/ statement. "ou ma& assume the values for f, x, and y have
alread& 'een declared as real values and initiali?ed.
f ( x)=
x
2
y if x0.0
x y if x>0.0
7.2.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 T&pe in the @uadratic e@uation program, compile, and e*ecute the program. .rovided input
values that will chec( each of the possi'le outputs.
24 8rite a /ortran program to prompt for and read the &ear that a person was 'orn. The &ear must
'e 'etween 1000 and 2000. -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
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.
4 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! 0600 B06BA BD6B! B6B0 A06AA AD6A! A6A0 D06D0 Z10
:ompile, and e*ecute the program. Test the program on a series of input values that will chec(
each grade.
1!
:hapter B M $election $tatements
14 8rite a /ortran 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 =
(
'
&
)
fahrenheit !2
The &ahrenheit value must 'e 'etween 610.0 and 110.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 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.
D4 8rite a /ortran 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, @uarters, 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.
A4 8rite a /ortran 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** /etters 1==i*iation
GF=: N=:
1 GFFU /<J
B G9+$ :=$
10 G9FJ .u'lic
1 GTNF +=:
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.
11
:hapter B K $election $tatements
1D
9 Loo"ing
8hen a series of /ortran statements need to 'e repeated, it is referred to as a loop or do)loop. +
/ortran do)loop is a special control statement that allows a /ortran 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 /ortran 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 se@uence of statements and is referred to as the
bod% of the do6loop. "ou can use an& e*ecuta'le statement within a do6loop, including -/6THEN6
E9$E6EN; -/ 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 e@ual 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.
/or 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 11. $ince the step was not specified, it is
defaulted 1.
1A
:hapter 0 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, , 1, A, 04.
+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
re@uired 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, , ..., n61, and n. Iore
precisel&, n\ U 1 Y 2 Y 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 , ..., the i
th
time with i and so on. Thus, the values that
1B
:hapter 0 M 9ooping
are multiplied with the initial value of factorial are 1, 2, , ..., n. +t the end of the do6loop, the value of
factorial is 1 Y 2 Y Y ... Y n which is nJ.
9. ,:IT 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.
/or 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 1 and the loop is e*ited without
completing the remaining iterations. 8hile it is possi'le to have multiple exit statements, t&picall& one
one is used. However, multiple e*it statements ma& 'e re@uired for more comple* pro'lems.
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.
/or e*ample, given the following declarations,
integer :: i
the following loop,
do i = 1, 10
if (i == 5) continue
write(*,*) i
end do
will displa& the num'ers from 1 to ! and D to 10.
9.! Counter Controlled ,xam"le
-n this e*ample we will write a /ortran program to find the difference 'etween the sum of the s@uares
and the s@uare of the sum of the first N natural num'ers.
10
:hapter 0 K 9ooping
;.3.1 9n'erstan' the Problem
-n order to find the difference 'etween the sum of the s@uares and the s@uare of the sum of the first N
natural num'ers, we will need to find 'oth the sum of the s@uares and the s@uare of the sum. /or
e*ample, the sum of the s@uares of the first ten natural num'ers is,
1
2
2
2
10
2
= B1
The s@uare of the sum of the first ten natural num'ers is,
1 2 10
2
= 11
2
= 021
Hence the difference 'etween the sum of the s@uares of the first ten natural num'ers and the s@uare of
the sum is 021 6 B1 U 2D!0.
The program will displa& the N value, the sum of the s@uares, the s@uare of the sum, and the difference
for each num'er from 2 to a given N value. The program should prompt for and read the N value. The
program will displa& appropriate headers.
;.3.2 Create the 4lgorithm
/or this pro'lem, first we will need to read the N value. Then, we will loop from 1 to the N value and
find 'oth the sum of the s@uares and the s@uare 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
/or convenience, the steps are written a program comments.
;.3.3 De6elop 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
D0
:hapter 0 M 9ooping
! 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
! display results
write(*,*) "Difference: ", difference
end program difference
The spacing and indentation is not re@uired, 'ut helps to ma(e the program more easil& reada'le.
;.3.4 0est:Debug the Program
/or 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'!rs or '!r*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 /ortran statements 'ased on a condition.
+s such, the loop ma& e*ecute a indeterminate num'er of times.
D1
:hapter 0 K 9ooping
<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 -/
statement, and an exit statement would 'e used to provide an means to terminate the looping.
/or 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 -/ statement, in an& form, can 'e used for
either the e*it of c&cle statements.
/or e*ample, a conditional loop could 'e used to re@uest 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.
D2
:hapter 0 M 9ooping
$ince a counter controlled ;< loop re@uires an integer loop counter, another use of conditional loops
would 'e to simulate a real counter. /or e*ample, to displa& the values from 1.1 to !.1 stepping '&
0.21, 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 adEusted as needed.
9.5 Conditionally Controlled Loo" ,xam"le
-n this e*ample we will write a /ortran 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 9n'erstan' the Problem
/or this limited e*ample, we will re@uest a date where the &ear is 'etween 10A0 and 2020. The month
must 'e 'etween 1 and 12. The date will depend on the month since some months have 0 or 1 da&s.
/e'ruar& has either 2B da&s or 20 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 4lgorithm
/or 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 1 da&s. The months
+pril, June, $eptem'er, and Novem'er have 0 da&s. /e'ruar& has 2B da&s unless the &ears is evenl&
divisi'le '& !, in which case /e'ruar& has 20 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
D
:hapter 0 K 9ooping
! 2 if modulo of year/4 is /= 0 28 days
! display results
/or convenience, the steps are written a program comments.
;.-.3 De6elop 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
! 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
D!
:hapter 0 M 9ooping
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 re@uired, 'ut helps to ma(e the program more easil& reada'le.
;.-.4 0est:Debug the Program
/or this pro'lem, the testing would 'e to ensure that the results match the e*pected value. This will
re@uire 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 @ui? @uestions and proEect suggestions 'ased on this chapter.
;.&.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat happen when an exit statement is e*ecutedN
24 How man& exit statements can 'e included in a loopN
4 8hat happen when an continue statement is e*ecutedN
!4 How man& continue statements can 'e included in a loopN
14 -f there are multiple c%cle statements in a loop, which one will 'e e*ecutedN
D1
:hapter 0 K 9ooping
D4 8hat is the output of the following /ortran 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
A4 8hat is the output of the following /ortran statements. +ssume i and + are declared as integer.
write(*,*) "start"
do i = 1, 3
do j = 1, 2
write(*,*) i, " * ", j, " = ", (i*j)
end do
end do
write(*,*) "end"
B4 +re the following /ortran statements valid or invalidN -f valid, what will happenN
do i = 3, 2
write(*,*) i
end do
04 +re the following /ortran statements valid or invalidN -f valid, what will happenN
do i = 3, 3
if ( i == 3 ) then
write(*,*) i
end do
end if
104 8hat is the limit of statements that can 'e included in a loopN
114 8hen an -/ 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 proEects.
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.
DD
:hapter 0 M 9ooping
4 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& 1 degrees for angles 'etween 1 and B1 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
0
2
g
cos - sin-
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 60.B1
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.0
)
Test the program on a series of different input values.
DA
Origin $m(act
,ime
``
:hapter 0 K 9ooping
DB
1< Formatted In"ut8&ut"ut
/ortran uses a /<)I+T statement to allow control on how data is displa&ed or read. This is useful
when ver& specific input or output is re@uired. /or e*ample, displa&ing mone& figures t&picall&
re@uire 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. /or 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 re@uires some amount of space. /or e*ample, an integer of four digits re@uires 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#
Description #peci=ier
-ntegers rIw or rIw.m
)eal r%w.d
9ogicals r/w
:haracters r1 or r1w
Hori?ontal .ositioning 3space4 nK
D0
:hapter 10 K /ormatted -nput5<utput
Hori?ontal .ositioning 3ta'4 4n
Fertical $pacing 0
-n addition, each specifier or group of specifiers can 'e repeated '& preceding it with a repeat count.
/ormat 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 73iD47 would loo( li(e#
x x x x x x
/ w .
/or 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& ,422.
Iultiple varia'les can 'e displa&ed. /or 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& ,!2122 with no spaces 'etween the two different values. However,
write (*,'(i2,i4)') num1, num2
will displa& ,42 1232 with one space 'etween the values. /urther,
write (*,'(3(i5))') num1, num2, num3
will displa& , 42 123 45672 where each varia'le uses 1 spaces.
A0
:hapter 10 M /ormatted -nput5<utput
1<.$ +eal Format '"ecifier
The real format specifier r0w.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 73fD.247 would loo( li(e#
x x x . x x
/ d .
/ w .
/or 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 var1 with no leading or
trailing spaces.
write (*,'(f3.1)') var1
8hich will displa& ,4.52 with no leading spaces. Iultiple varia'les can 'e displa&ed. /or e*ample,
to displa& the values in varia'les var1 and var2.
write (*,'(f5.2,f8.3)') var1, var2
8hich will displa& , 4.50 12.0002. +nother e*ample with three varia'les, var1, var2, and var3, is
as follows#
write (*,'3(f10.4))') var1, var2, var3
8hich will displa& , 4.5000 12.0000 2145.57802 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 10 positions in which 21
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 r#w 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.
A1
:hapter 10 K /ormatted -nput5<utput
/or e*ample, given the declarations,
logical :: dooropen=.true., windowopen=.false.
the following write statement can 'e used to displa& the value in the logical varia'les dooropen and
windowopen with no leading or trailing spaces.
write (*,'(l1,1x,l1)') dooropen, windowopen
8hich will displa& ,T F2. *ote, the *1 format is lower6case 9 and num'er 1.
The si?e or width can 'e adEusted as needed. /or e*ample, the following write statement,
write (*,'(l4,2x,l5)') dooropen, windowopen
will displa& ,True False2 3with two spaces4.
1<.0 Character Format '"ecifier
The real format specifier r&w 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 73aD47 would loo( li(e#
c c c c c c
/ w .
/or 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 (*,'(a11)') msg
8hich will displa& ,Hello World2. The count is not re@uired when using the character format
specifier. /or e*ample, the statement,
write (*,'(a)') msg
will displa& the same ,Hello World2 string. Iultiple varia'les or strings can 'e displa&ed. +lso, the
count can 'e used to displa& a portion of the string. /or e*ample, to displa& the string in varia'le msg
and the string ,Good '&e cruel world2.
write (*,'(a9,2x,a)') msg, "Good bye cruel world"
8hich will displa& ,Hello Wor Good bye cruel world2 to the screen. Note that of the 11
character string, onl& the first 0 characters are displa&ed.
A2
:hapter 10 M /ormatted -nput5<utput
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.
/or 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<.9 ,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.
A
:hapter 10 K /ormatted -nput5<utput
1<.7.1 9n'erstan' the Problem
/or 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.
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 daynum is 0 for a $unda&, 1 for a Ionda&, 2 for a Tuesda&, etc.
1<.7.2 Create the 4lgorithm
/or 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&. /or 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 1, it is customar&
to displa& a ,012 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 306D4 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
/or convenience, the steps are written a program comments.
1<.7.3 De6elop 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
A!
:hapter 10 M /ormatted -nput5<utput
! ----------
! display initial header
write(*,*) "Date Formatting Example"
! 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
A1
:hapter 10 K /ormatted -nput5<utput
! ----------
! 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 "
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 re@uired, '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<.7.4 0est:Debug the Program
/or 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
AD
:hapter 10 M /ormatted -nput5<utput
different input values and verif& that the output is correct for those input values.
1<.9 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
1<.;.1 Quiz Questions
=elow are some @ui? @uestions.
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
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"
4 ;escri'e the output of the following code fragment 3 pts4#
Note, 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 000 3right Eustified, no leading ?ero7s, no additional spaces4.
14 8hat is the write statement and format specifier to output the real value of pi which has 'een
initiali?ed to .1!110 3right Eustified, no additional spaces4N
D4 8hat is the single write statement and format specifier to output L.rogrammingL and L-s /un\L
on two different linesN
A4 8hat is the single write statement and format specifier to output LEnter Num'er#L and leave the
cursor on the current lineN
1<.;.2 uggeste' Pro(ects
=elow are some suggested proEects.
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.
AA
:hapter 10 K /ormatted -nput5<utput
24 Update 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 14, including chec(ing for a valid date for the
specific month, and ensure that the value for &ear is 'etween 10A0 and 000 3inclusive4. /or
e*ample, +pril 1 is not a valid date. +dditionall&, the program should chec( for a leap &ear to
see if /e'ruar& has 2B or 20 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.
4 8rite a /ortran 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#
payment = 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 /ortran 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 )
year
*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.
AB
11 Characters and 'trings
/ortran was originall& developed for scientific and engineering application re@uiring significant
mathematical calculations. However, the /ortran 01 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 @uotes. /or 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 @uotes, it is treated as a character and conse@uentl&
arithmetic operations 3addition, su'traction, etc.4 are not allowed.
+ string is a series of characters. + string consists of an ar'itrar& se@uence of characters also enclosed
in @uotes. $ome e*amples include#
"Hello World."
"456"
"1 2 3"
"456?"
"Good bye cruel world!!"
"Have a nice day?"
$ince digits enclosed in @uotes are not numeric values, the strings ,1 2 2 and ,!1DN2 are allowed.
+ pro'lem arises if &ou want to have a @uote in the string itself. + dou'le @uote will 'e interpreted as a
single within a string. The two @uotes must 'e together 3no spaces 'etween4. /or e*ample, the string#
"He said ""wow"" when he heard"
8ould 'e displa&ed as
"He said "wow" when he heard"
The dou'le6@uote is sometimes referred to as an escape character. $trings and characters must 'e
associated with the character data t&pe.
A0
:hapter 11 K :haracters and $trings
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&.
This is performed with a t&pe declaration statement in the form of#
<type> :: <list of variable names>
/or character varia'les, the t&pe is ,character2. /or 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, dayofwee1, with a ma*imum length of 0 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 re@uired, separate declaration lines are re@uired.
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 re@uired, 'ut can sometime 'e convenient. /or e*ample, to define an character
varia'le, dayofwee1, 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, e@ual signs, semicolons, and commas are allowed.
Faria'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. /or e*ample, to define an character constant, lang,
character(len=7), parameter :: lang="English"
B0
:hapter 11 M :haracters and $trings
To save counting the characters, the ,Y2 can 'e used. /or e*ample,
character(len=*), parameter :: university="UNLV"
This instructs the /ortran compiler to count the characters and set the appropriate length.
11.5 Character %ssignment
+ssignment is term for setting a character varia'le e@ual to some value 3character or string4.
+ssignment is performed with a e@ual 3U4 sign. /or 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&. /or e*ample, if the varia'le thismonth is reset
thismonth = "May"
The varia'le thismonth contains ,Ia& 2 3e.g., ,Ia&2 with an additional D 'lan(s4.
11.0 Character &"erators
The onl& character operator is ,552 3concatenation4 which simpl& concatenates two strings together. /or
e*ample,
"University of" // "Nevada Las Vegas"
:haracters varia'les and literals ma& 'e used with concatenation. /or 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 str3 to ,+=:;E/12!1D2.
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 e@ual to the stop position.
B1
:hapter 11 K :haracters and $trings
/or 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 str3 to ,+=:!1D2.
11.9 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 ,02, 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#
%unction Description
+:H+)3-4 )eturns the character represented '& integer argument -
'ased on the +$:-- ta'le 3+ppendi* +4. -nteger argument -
must 'e 'etween 1 and 12A.
-+:H+)3:4 )eturns the integer value of the character argument :
represented '& +$:-- ta'le 3+ppendi* +4.
9EN3$T)4 )eturns an integer value representing the length of string
argument $T).
B2
:hapter 11 M :haracters and $trings
9ENRT)-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* ;.
11.1< ,xam"le
This e*ample will scan a string and convert all lower6case letter to upper6case.
11.1<.1 9n'erstan' the Problem
/or this pro'lem, the string will 'e read from the user with a ma*imum of B0 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 4lgorithm
/or 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
/or convenience, the steps are written a program comments.
B
:hapter 11 K :haracters and $trings
11.1<.3 De6elop the Program
=ased on the algorithm, the 'elow program could 'e developed.
program caseconverter
! declare variables
implicit none
integer :: i, strlen
character(80) :: string1
! ----------
! 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 re@uired, 'ut helps to ma(e the program more easil& reada'le.
B!
:hapter 11 M :haracters and $trings
11.1<.4 0est:Debug the Program
/or this pro'lem, the testing would ensure that the output string is correct for the given input.
/or 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.
11.11 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
11.11.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat is the declaration for a character varia'le, msg, to contain the string ,Hello World!2N
24 Given 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.
B1
:hapter 11 K :haracters and $trings
4 Given the following /ortran 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, astr2, astr3, and astr24.
!4 How can the integer value 3'ased on the +$:-- ta'le4 of a character 'e o'tainedN
14 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 proEects.
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 Update 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.
4 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 1 strings 3_ B0 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.
BD
1 File &"erations
/ile operations allow /ortran 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*ause E+p*anation
unit Unit num'er for su'se@uent file operations 3i.e.,
read, write, etc.4. T&picall& an integer 'etween 10
and 00.
=i*e Name of file to 'e opened. :an 'e @uoted or a
character varia'le.
status $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.
position .osition or place to start. +llowa'le options are
,rewind2 3'eginning4, ,append2 3end4.
BA
:hapter 12 K /ile <perations
iostat Name 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 00.
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. Normall&, 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.
/or e*ample to open a file named temp.t*t and place the string ,/ortran E*ample2 and the num'ers !2,
and .1!110 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 /ortran 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.
The general form of the write statement is as follows#
read (unit=<unit number>, fmt=<format statement>, &
iostat=<variable>) <variables/expressions>
BB
:hapter 12 M /ile <perations
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.
/or e*ample, if the file numbers.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 /ortran 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 read information from 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'se@uent 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.
B0
:hapter 12 K /ile <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.
/or 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 /ortran program to read an input file and write a line num'er and the
original line to an output file.
12.2.1 9n'erstan' the Problem
/or 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.2.2 Create the 4lgorithm
/or 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
written to the output file. /or this e*ample, we will assume that a line will have 12 or less characters.
00
:hapter 12 M /ile <perations
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
/or convenience, the steps are written a program comments.
12.2.3 De6elop 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: "
01
:hapter 12 K /ile <perations
! read output file name
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 re@uired, 'ut helps to ma(e the program more easil& reada'le.
12.2.4 0est:Debug the Program
/or 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.9 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
02
:hapter 12 M /ile <perations
12.7.1 Quiz Questions
=elow are some @ui? @uestions.
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
4 /or 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'se@uent 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, has 'een successfull& opened using unit num'er 20,
and contains the following data#
"line 1 data1=23 data2 =034 data3 =05123"
8hat is the read statement re@uired to get data1, data2, and data into the integer varia'les
num1, num2, and num3 respectivel&.
12.7.2 uggeste' Pro(ects
=elow are some suggested proEects.
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.
0
:hapter 12 K /ile <perations
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
A
. 8rite a /ortran 01 program to
generate the 3*,&4 coordinates for a spirograph drawing.
/irst, the program should prompt for an output file name, read the file name, and open the file.
-f the file can not 'e opened, the program should displa& an appropriate error message and re6
prompt. Ne*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'se@uent 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
) cos( step)) + offsetposition cos
(
(radius
1
+radius
2
)
step
radius
2
)
y=((radius
1
+radius
2
) sin(step)) + offsetposition sin
(
(radius
1
+radius
2
)
step
radius
2
)
The step should start at 0.0 and stop at D0.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.
4 8rite a /ortran program that pla&s the :haos Game. To pla& the :haos Game, plot points +,
=, : and an ar'itrar& initial point J1. Then, generate a random num'er 'etween 1 and
representing +, =, or :. -f + comes up, plot the midpoint of the line Eoining J1 to +. -f =
comes up, plot the midpoint of the line Eoining J1 to =P the case with : is similar. :all this
new point J2. )oll the die again. .lot the midpoint of the line Eoining J2 to either +, = or :
depending on the outcome of the die toss. :all this new point J. )epeat this process N times.
Test the program on a num'er of different input values.
Note, the correct output of this program is shown on the cover page.
A /or more information, refer to# http#55en.wi(ipedia.org5wi(i5$pirograph
0!
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*.
/or e*ample, a single dimension arra& might loo( li(e#
inde* value
+rra& Name 1 Zvalue[
2 Zvalue[
. . .
. . .
Zvalue[
n Zvalue[
The specific s&nta* re@uires 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, nameN are names of one or more arra&s 'eing declared.
01
:hapter 1 K $ingle ;imension +rra&s
/or 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. /or e*ample,
a declaration of#
integer, dimension(-5:5) :: ranges
will create an arra&, ranges, with inde*es 'etween 61 and 1 3inclusive4. Using inde* values not within
the specified range will result in an error.
13.1.2 tatic 4rray 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. /or e*ample, to declare an arra& named costs with ! elements and set the four
elements to 10.0, 11.0, 20.0, and 21.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 11.0, costs34 is set to 20.0, and costs3!4 is set to 21.0.
+dditionall&, after declaration, it is possi'le to initiali?e all elements of an arra& to a single value with
an assignment statement. /or e*ample,
costs = 0
will set all four elements of the costs arra& to ?ero.
13.1.3 Dynamic 4rray 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.
0D
:hapter 1 M $ingle ;imension +rra&s
/or 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 4rray 4llocation
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.
/or 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>)
/or e*ample, given the declaration,
real, dimension(10) :: times
would declare an arra& with ten elements. To place a value 121. in the first arra& element,
times(1) = 121.3
+nd to place 0B.121 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.
0A
:hapter 1 K $ingle ;imension +rra&s
/or 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 0B.D in the fifth arra& element,
temps(i) = 98.6
To access the fifth element, su'tract .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 i = 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&. /or 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 1 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.
0B
:hapter 1 M $ingle ;imension +rra&s
/or 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 1 elements in the arra& num'ers to 1.0, 2.0, .0, !.0, and 1.0 respectivel&.
The implied do6loop ma& also 'e used. /or e*ample, in the following declaration,
integer, dimension(5) :: numbers = (/ (i, i=1,5) /)
will initiali?e each of the 1 elements in the arra& num'ers to 1, 2, , !, and 1 respectivel&.
1!.5 ,xam"le
-n this e*ample we will write a /ortran 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
B
.
The standard deviation is calculated as follows#
standard deviation =
i =1
n
( averagelist ( i ))
2
n
+s such, the average must 'e calculated 'efore the standard deviation.
13.-.1 9n'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&. /or this pro'lem,
there will 'e no more than 1000 num'ers in the file. +fter the num'ers are in the arra&, the minimum,
ma*imum, and sum will 'e found. Ne*t, the average can 'e computed. /inall&, 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 4lgorithm
+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
B /or more information, refer to# http#55en.wi(ipedia.org5wi(i5$tandardRdeviation
00
:hapter 1 K $ingle ;imension +rra&s
! loop
! prompt for file name
! read file name
! attempt to open file
! 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 from the file
! if error on read, terminate program
! if end of file, exit loop
! increment number counter
! place number in array
! end loop
Ne*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. /inall&, 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.
100
:hapter 1 M $ingle ;imension +rra&s
<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
! display results
! end program
/or convenience, the steps are written a program comments.
13.-.3 De6elop the Program
=ased on the algorithm, the 'elow program could 'e developed.
program standardDeviation
! declare variables
implicit none
integer :: i, ncount=0, errs=0, 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
101
:hapter 1 K $ingle ;imension +rra&s
! if >3 errors, terminate program
if (errs > 3) then
write (*,'(a)') "Sorry your having problems."
write (*,'(a)') "Program terminated."
stop
end if
! end loop
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
102
:hapter 1 M $ingle ;imension +rra&s
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
std = sqrt ( stdsum / real(ncount) )
! display results
write (*,'(a)') "-------------------------------"
write (*,'(a)') "Results:"
do i = 1, ncount
write(*,'(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 re@uired, 'ut helps to ma(e the program more easil& reada'le.
13.-.4 0est:Debug the Program
/or 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.
10
:hapter 1 K $ingle ;imension +rra&s
/or 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. /or 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 @ui? @uestions and proEect suggestions 'ased on this chapter.
13.2.1 Quiz Questions
=elow are some @ui? @uestions.
14 E*plain wh& an arra& is considered a direct access structure.
24 :an arra&s hold integer values 3&es5no4N
4 :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&, ivalues, with 10 real elements.
c4 +n arra&, inums, with $-WE1 integer arguments.
d4 +n arra&, counts, with 10 real elements whose su'script values range from 0 to 0.
14 Given the declarations and the following 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) e@ualN
'4 8hat does arr(1) + arr(2) e@ualN
c4 8hat does arr(1+2) e@ualN
d4 8hat does arr(k) e@ualN
10!
:hapter 1 M $ingle ;imension +rra&s
D4 8hen can an arra& 'e allocated 3two options4N
A4 Given the following statements#
integer, dimension(5) :: nums
integer :: i=1
nums = 0
do
if ( i == 5 ) exit
if ( mod(i,2) == 0) then
nums(i) = 99
else
nums(i) = i
end if
i = i + 1
end do
a4 what values are in arra& after e*ecution
'4 8hat is the (nums(i), i=1,5) referred to asN
c4 8hat does write(*,'(1x,i2)') (nums(i), i=1,5) displa&. Note, use an unederscore
3,R24 for to show the spaces.
13.2.2 uggeste' Pro(ects
=elow are some suggested proEects.
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 /ortran 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.
4 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
!
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.
101
:hapter 1 K $ingle ;imension +rra&s
!4 8rite a /ortran 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 /ortran code. Test the program
on a series of different input values.
10D
1$ 6ultidimensional %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 &, 3, %, etc. are the arra& columns and the
num'er is li(e the row.
/or e*ample, a two dimension arra& might loo( li(e#
inde* 1 2
+rra& Name 1 Zvalue[ Zvalue[
2 Zvalue[ Zvalue[
. . . . . .
. . . . . .
Zvalue[ Zvalue[
n Zvalue[ Zvalue[
The specific s&nta* re@uires 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& Name 1 arr31,14 arr31,24
2 arr32,14 arr32,24
arr3,14 arr3,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
re@uires a si?e for each dimension. +s 'efore, there are two wa&s to declare an arra&# static and d&namic.
10A
: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 si?e, and name1,
name2, ... , nameN are names of one or more arra&s 'eing declared.
/or 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 10,000 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. /or e*ample, a declaration of#
integer, dimension(0:9,0:9) :: ranges
will create an arra&, ranges, with 'oth inde*es 'etween 0 and 0 3inclusive4. Using 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.
/or 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 4rray 4llocation
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
10B
:hapter 1! M Iultidimensional +rra&s
indicating the status 3success or failure4 of the operation. +s 'efore, if 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.
/or e*ample, given the declarations,
integer, dimension(:,:), allocatable :: nums2
integer :: allstat
the following allocate statement allocates space for 10,000 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 allstat 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>)
/or e*ample, given the declaration,
real, dimension(10,5) :: table1
would declare an arra&, table1, with a total of 10 elements. To place a value 121. in the first row and first
column,
table1(1,1) = 121.3
+nd to place 0B.121 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. /or 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 0B.D in the second row, fourth column,
tmptable(i,j+1) = 98.6
To access the same element, su'tract .0 and place the result 'ac( into the same location,
tmptable(i,j+1) = tmptable(i,j+1) 3.0
100
: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 /ortran program that will re@uest a count, generate count 3x,y4 random
points, and perform a Ionte :arlo > estimation 'ased on those points. +ll x and y values are 'etween
0 and 1. The main routine will get the count and the use a su'routine to generate the random 3x,y4
points and a function, to perform the Ionte :arlo > estimation. /or this e*ample, the count should 'e
'etween 100 and 1,000,000.
14.3.1 9n'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,y4 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 s@uare is centered on the origin of a
:artesian plane, and the s@uare has sides of
length 2. -f we inscri'e a circle in the s@uare, it
will have a diameter of length 2 and a radius of
length 1. -f we plot points within the upper right @uadrant, the ratio 'etween the points that land within
the inscri'ed circle and the total points will 'e an estimation of >.
est = 4
(
samp*es inside circ*e
tota* samp*es
)
+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
110
: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 s@uare root of
3x
2
Oy
2
4 Z 1.0, the random point is within the circle.
/inall&, the figure we are discussing, a s@uare centered on the origin with an inscri'ed circle is
s&mmetric with respect to the @uadrants 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 4lgorithm
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,y4 points. =ased on the pro'lem definition, each point should 'e 'etween 0.0 and
1.0 which is provided '& default '& the /ortran random num'er generator. Ne*t, the program can
perform the Ionte :arlo pi estimation. This will re@uire the alread& populated 3x,y4 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+ y2) 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
(
samp*es inside circ*e
tota* samp*es
)
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
/or convenience, the steps are written a program comments.
111
:hapter 1! K Iultidimensional +rra&s
14.3.3 De6elop 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)
112
:hapter 1! M Iultidimensional +rra&s
call random_number(y)
! place (x,y) values in array
pts(i,1) = x
pts(i,2) = y
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 re@uired, 'ut helps to ma(e the program more easil& reada'le.
14.3.4 0est:Debug the Program
/or 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.
11
:hapter 1! K Iultidimensional +rra&s
1$.$ ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
14.4.1 Quiz Questions
=elow are some @ui? @uestions.
14 :an a multidimensional arra& simultaneousl& hold 'oth integer and real values 3&es5no4N
24 Iultiple choice# what is the order of the inde*esN
a4 3row, column4
'4 3column, row4
c4 3row, row4
d4 3column, column4
e4 user6selecta'le
*ote, there is onl& one correct answer.
4 Given 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.
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 proEects.
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.
11!
:hapter 1! M Iultidimensional +rra&s
24 Update 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.
4 Update 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.
14 Update the find ma*imum program 3from the previous @uestion4 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.
D4 8rite a /ortran program to construct an odd6order Iagic $@uare
0
. The algorithm for
constructing an N*N odd ordered Iagic $@uare is as follows#
/irst, place a 1 in the middle of the top row.
+fter placing an integer, 1, move up one row and one column to the right to place the
ne*t integer, 141, 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 s@uare 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 s@uare or if &ou move out of the s@uare at
the upper right hand corner, place 141 immediatel& 'elow 1.
Test the program and compare the results to the 8i(ipedia e*ample.
0 /or more information, refer to# http#55en.wi(ipedia.org5wi(i5IagicRs@uare
111
:hapter 1! K Iultidimensional +rra&s
11D
15 'ub"rograms
Until 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 proEects,
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
/ortran 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 /ortran 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 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.
11A
:hapter 11 K $u'programs
1-.2.1 ,nternal Routines
-nternal routines re@uire 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. /or larger programs e*ternal routines would 'e used e*tensivel&.
However, additional set6up statements, including an external declaration and an inter&ace bloc., are
re@uired. The definition and use of e*ternal routines is not addressed in this chapter.
15.! %rguments
8hen writing and using /ortran 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 4rgument ,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 7sing 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.
11B
:hapter 11 M $u'programs
1-.-.1 4rgument 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 5outine
...
call example (x, y, z)
...
#u3routine
...
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 /ortran 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 /ortran functions are descri'ed in the following sections.
1-.&.1 ,ntrinsic %unctions
+s 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* ;.
110
:hapter 11 K $u'programs
1-.&.2 9ser3De=ine' %unctions
+ user6defined function are functions that a written '& the user for specific or speciali?ed re@uirements.
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 /ortran 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 /ahrenheit 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 /ahrenheit 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, &ahr/to/celsius, 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. None of the e*amples in this te*t will include or
utili?e side6effects.
15.5 'ubroutines
+ su'routine is a /ortran su'program that can accept some (ind of input information and 'ased on that
information, return a result or series of results.
120
:hapter 11 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.
/or 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, 01, 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, 02, 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. Faria'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\
121
:hapter 11 K $u'programs
15.9 ,xam"le
-n this e*ample we will write a /ortran 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&,
trac( the count of games won and lost, and displa& some win5loss statistics. + su'routine will 'e used
to pla& the Twent&6$i* game. The su'routine will 'e called as man& times as re@uested.
The su'routine, twenty5six67, will pla& the game dice game Twent&6$i*. To pla& the game, the pla&er
rolls the dice 31 to D4 and this initial roll is used as the ,point2 num'er. Then the pla&er throws the ten
dice 1 times. The score is the num'er of times that the point num'er is thrown. + random num'er
'etween 1 and D 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 -.
-/ '
01 2
03 '
04 1
0& 4
/. -.
Other .
The su'routine should displa& the dice 3all 10 dice for each of 1 rolls4, point count, game result,
pa&out. /or e*ample, if the point was D, 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
/or this e*ample, the main will trac( the games won and lost.
10 /or more information, see# http#55homepage.ntlworld.com5dice6pla&5Games5Twent&$i*.htm
122
:hapter 11 M $u'programs
1-.7.1 9n'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 verif& that the count is 'etween 2 and 1,000,000 3ar'itraril&
chosen4. Then, the program will call the twenty5six67 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 twentySix (payout)
if (payout > 0) then
games_won = games_won + 1
else
games_lost = games_lost + 1
end if
12
:hapter 11 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-.7.2 Create the 4lgorithm
$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 D 3for a dice4. The initial point value must first 'e esta'lished
followed '& a loop to throw the ten dice 1 times in accordance with the game rules. The results will
'e stored in a two6dimensional arra&. 8hile not strictl& re@uired, it does provide an additional e*ample
of how to use a two6dimensional arra&. /inall&, 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
/or convenience, the steps are written a program comments.
12!
:hapter 11 M $u'programs
1-.7.3 De6elop the Program
=ased on the algorithm, the 'elow program could 'e developed.
! *********************************************************
! Subroutine to simulate twenty-six game.
! 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 twentySix (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
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
121
:hapter 11 K $u'programs
case (30)
payout = 10
case default
payout = 0
end select
write (*,'(/,5x,a,/,5x,a,i2,/,5x,a,i2)') &
"--------------------------------------", &
"Point: ", point
do i = 1, 13
write (*,'(8x, a, i2, 2x, a, 10(2x, i1),/)', &
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 twentySix
The spacing and indentation is not re@uired, 'ut helps to ma(e the program more easil& reada'le.
1-.7.4 0est:Debug the Program
/or 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 @ui? @uestions and proEect suggestions 'ased on this chapter.
1-.;.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat are the two t&pes of /ortran su'programsN
12D
:hapter 11 M $u'programs
24 How man& values does a user6defined function t&picall& returnN
4 -n the function call, ans = power(x, y), what are x and y are calledN
!4 -n the function heading, integer function power(a, b), what are a and b are calledN
14 -n the function, integer function power(a, b), what is the t%pe of the value returnedN
D4 -s it possi'le to pass integer arguments to a real function 3&es5no4N
A4 The su'program section 3where functions and su'programs are defined4 is mar(ed '& what
(e&wordN
B4 8hat is the output of the following function#
integer function power(a, b)
integer, intent(in) :: a, b
power = a ** b
return
end function power
a4 with the input of a U 2 and b U N
'4 with the input of a U and b U 2N
04 Given the following programN
program quiz
implicit none
real :: temp=80.0, temp1=50.0, temp2
write (*, '(f5.2, 2x, f5.2)') temp, temp1
temp2 = fahrToCelsius(temp1)
write (*, '(f5.2, 2x, f5.2)') temp, temp2
contains
real function fahrToCelsius(temp)
real, intent(in) :: temp
fahrToCelsius = (temp 32.0) / 1.8
return
end function fahrToCelsius
end program quiz
a4 8hat is the name of the functionN
'4 -s the a'ove program correct 3&es5no4N
c4 ;oes the varia'le temp in the main and the varia'le temp in the function refer to the same
valueN
12A
:hapter 11 K $u'programs
d4 8hat is the outputN
104 8hat is meant '& the term 'ariable scopeN
114 8hat is the correct intent for the following situations#
a4 + varia'le passed to a function that will not 'e changed in the function.
'4 + varia'le that will 'e set in the su'routine and returned. No value is passed in.
c4 + varia'le that will 'e passed into a su'routine, updated, and returned 'ac( to the calling
routine.
124 8hat is a meant '& the term side$e&&ectN
1-.;.2 uggeste' Pro(ects
=elow are some suggested proEects.
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.
24 8rite a main program and an integer /ortran function, g'eries67, to compute the following
geometric series#
g =
n=0
n1
x
n
= 1+x+x
2
+x
!
+ +x
( n1)
The arguments for the call, in order, are as followsP n 3integer value4. The function should
return an integer result 3of the formula 'ased on the n value4. The main should call the function
with several different values.
4 8rite a main program and a real function, harmonic8ean67, 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 =
N
(
1
x
1
+
1
x
2
+...+
1
x
N
)
The arguments for the call, in order, are as followsP arra& of num'ers 3with count real values4,
count 3integer4. The function should return an real result 3of the formula4. The main should call
the function with several different values.
12B
:hapter 11 M $u'programs
!4 8rite a main program and a su'routine, %ircle'tats67, 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.
14 8rite a main program and a su'routine, 9ead%oord67, to read an 3x, y, z4 coordinate from the
user. The su'routine must prompt for and read 3x, y z4 and ensure that the x, y, 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, y, 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, y 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.
D4 8rite a main program and a su'routine, 'tats67, 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.
120
:hapter 11 K $u'programs
10
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.
/or 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 re@uired. 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
/or 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 re@uired, '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 re@uired 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.
11
:hapter 1D 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)>
/or 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. /irst the varia'le name is specified, followed '& a ,c2 3percent sign4, and then the
component name. The general format is#
<variable_name>%<component_name>
/or e*ample, to set all components for the student student1, the following
student1%name = "Joseph"
student1%id = 1234
student1%score = 99.99
student1%grade = "A"
Each component for student1 is set individuall&. Not ever& component must 'e set. <f course, as with
other varia'les, an component that has not 'een set can not 'e used.
12
:hapter 1D M ;erived ;ata T&pes
This previous declaration and these assignments will esta'lish a varia'le as follows#
student name
Joseph
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. /or e*ample,
to set student2 to 'e 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. /or this e*ample, the time will consist of hour, minutes,
seconds in 2!6hour format. /or this e*ercise, the hours ma& e*ceed 2 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 9n'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 re@uires that hours range from 0 to 2, minutes range from 0 to
10, and seconds range from 0 to 10. Falues outside these ranges, D0 seconds for e*ample, are not valid.
/or 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 D0, the seconds must 'e adEusted 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 2 hours.
/or e*ample, given time one as 1! hours, !A minutes and 22 seconds 3i.e., 1!#!A#224 and time two as 1B
hours, 22 minutes, and 10 seconds, 3i.e., 1B#22#104, the total time would 'e hours, 10 minutes and 12
seconds 3i.e., #10#124.
1
:hapter 1D K ;erived ;ata T&pes
1&.4.2 Create the 4lgorithm
/or 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
/or convenience, the steps are written a program comments.
1&.4.3 De6elop 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
1!
:hapter 1D M ;erived ;ata T&pes
type time
integer :: hours, minutes, seconds
end type time
! 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. &
11
:hapter 1D K ;erived ;ata T&pes
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
! *******************************************************
! 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.
1D
:hapter 1D M ;erived ;ata T&pes
1&.4.4 0est:Debug the Program
/or 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. /or e*ample, to declare an arra& named class to
hold 0 elements of t&pe student, the following declaration can used used.
type(student), dimension(30) :: class
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. /or an arra& of t&pe3student4, the la&out would 'e as follows#
class314 name
id
score
grade
class324 name
id
score
grade
class34 name
id
score
grade
. . . . . .
To access elements in the arra&, an inde* must 'e used. +fter the inde*, the desired component would
'e specified. /or 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.
1A
:hapter 1D K ;erived ;ata T&pes
+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)
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 10 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. /inall&, 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 9n'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 D0 characters4 and score from the user. Names 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. /or 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.
+ = : ; /
+[U00 B0 6 B0 A0 6 A0 D0 6 D0 ZU10
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.
1B
:hapter 1D M ;erived ;ata T&pes
1&.&.2 Create the 4lgorithm
/or 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
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
10
:hapter 1D K ;erived ;ata T&pes
/or convenience, the steps are written a program comments.
1&.&.3 De6elop 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
! 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
1!0
:hapter 1D M ;erived ;ata T&pes
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
! update count of students and place 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
! check each score / set each grade
do i = 1, count
select case ( nint(class(i)%score) )
case (90:)
1!1
:hapter 1D K ;erived ;ata T&pes
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
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 0est:Debug the Program
/or this pro'lem, the testing would involve e*ecuting the program and entering a series of student data
values to ensure that the results are correct. -f 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 @uic(l& identified. <nce identified, some additional write statements inside
the su'program can 'e used to help identif& the specific pro'lem. The testing and de'ugging process is
left to the reader as an e*ercise.
1!2
:hapter 1D M ;erived ;ata T&pes
10.5 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
1&.2.1 Quiz Questions
=elow are some @ui? @uestions.
14 +n item in a derived data t&pe is calledN
24 How are components of a derived data t&pe accessedN
4 ;efine a derived data t&pe, circle, to store information a'out a circle. Iust include a circle
name 3ma* 20 characters4, si?e 3radius C a real value4 and the position in 6dimensional space
3x, y, and z Q all integer values4.
!4 8rite the declaration necessar& to declare two varia'les named ring1 and ring2 of t&pe circle
3from previous @uestion4.
14 ;efine a user6defined t&pe, planet, to store information for a planet. -nclude a name 311
characters4, radius 3real value4, area 3real value4, and volume 3real value4. +dditionall&, write
the declaration necessar& to declare two varia'les named earth and mars of t&pe planet+
D4 ;efine a user6defined t&pe named date for processing dates consisting of a month name 310
characters4, month 3integer4, date of month 3integer4, and &ear 3integer4.
A4 =ased on the previous @uestion
a4 8rite the statements to declare a varia'le named today and set it to 125215201.
'4 8rite the statements to declare a varia'le named newyear and set it to Januar& 1, 2011.
1&.2.2 uggeste' Pro(ects
=elow are some suggested proEects.
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 /ortran program to read and displa& information a'out a set of planetar& 'odies. The
program should read the information from a file, allow the user 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 read"lanets67 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 calc"lanet&rea67 to calculate the planet area 'ased on the diameters.
1!
:hapter 1D K ;erived ;ata T&pes
/unction get:ser*ption67 to displa& a list of options, read the selection option.
$u'routine display"lanet8in8ax67 to displa& the minimum and ma*imum 'ased on an
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 34 Q .lanets with $hortest and 9ongest ;a&s 3'ased on da& length4
$u'routine print"lanets'ummary67 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.
4 Iodif& the planet program 3from previous @uestion4 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.
14 Iodif& the class scores program to assign grades 'ased on the following scale#
% D C9 C CA )9 ) )A 19 1 1A
09'& ,09$0 $09$2 $!9$, $$9$& .09.2 .!9., .$9.& &09&2 &!9&, &$9100
Test on several sets of input values and verif& that the output is correct for the given input.
D4 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.
1!!
15 6odules
/or larger programs, using a single source file for the entire program 'ecomes more difficult.
/ortunatel&, 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 re@uirements and an e*ample of how to set6up the modules.
15.1 6odule #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>
/or 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
1!1
:hapter 1A K Iodules
This e*ample assumes the real arra& contains len num'er of values up to a ma*imum of 1000 values.
15. 7se 'tatement
<nce the module is defined, the routines from the module can 'e included '& using the use statement.
The use statement or statements must 'e at the 'eginning of the applica'le source file. /or 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.! 7"dated Com"ilation Commands
/or a large program that is split 'etween multiple source files, the compilation process must 'e
updated. The compilation process refers to the steps re@uired 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. /urther, for ver& large proEects, multiple programmers
can wor( on separate modules simultaneousl&.
1!D
:hapter 1A M Iodules
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'Eect file stats.o and a
module file stats.mod. The name of the o'Eect 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 re@uirement.
The compile command is re@uired 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.
/or e*ample, the command to compile the main file for the previous arra& average e*ample is#
gfortran -o main main.f95 stats.o
/or 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 re@uired and used at this
step.
15.$ 6odule ,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.
12.4.1 9n'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 re@uire 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#
surface&rea = 4.0 radius
2
volume =
4.0
!.0
radius
!
The value of > will 'e defined as a constant and set to .1!110.
/or 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.
1!A
:hapter 1A K Iodules
12.4.2 Create the 4lgorithm
=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
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.
12.4.3 De6elop 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 re@uire multiple files, the
program is split in order to provide an e*ample using a separate module file.
12.4.3.1 5ain 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)
1!B
:hapter 1A M Iodules
! -----
! 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.
12.4.3.2 5o'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. Use 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
return
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
1!0
:hapter 1A K Iodules
sphereSurfaceArea = 4.0 * pi * radius ** 2
return
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
write (*,'(3x, a, f10.2, /)') &
"Sphere Surface Area = ", area
return
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 re@uire a more comprehensive
design effort.
12.4.4 Compile the Program
The commands to compile the module file and then the main file are as follows#
gfortran -c sphereroutines.f95
gfortran -o modmain modmain.f95 sphereroutine.o
The first will create files sphereroutines.o and sphereroutines.mod. The second will read the
files modmain.f95 and sphereroutines.o then create the e*ecuta'le modmain.exe file.
12.4.- 0est:Debug the Program
/or 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 @uic(l& identified. <nce identified, some additional write statements inside the
su'program can 'e used to help identif& the specific pro'lem.
110
:hapter 1A M Iodules
15.5 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
12.-.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat is the primar& purpose of using a moduleN
24 -n the main program, what statement is used to include the modulesN
4 -n the secondar& source file, what statements is used to define and name the moduleN
!4 How man& main programs are allowedN
14 How man& modules are allowedN
D4 -s the contains (e& word needed in a module file 3&es or no4N
12.-.2 uggeste' Pro(ects
=elow are some suggested proEects.
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.
4 Update 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.
111
:hapter 1A K Iodules
112
19 +ecursion
The Google search result for recursion, shows 1ecursion did %ou mean recursionN
)ecursion is a powerful general6purpose programming techni@ue and is used for some important
applications including search and sorting methods. )ecursion is the idea that a function ma& call itself
3which is the 'asis for the Eo(e4.
)ecursion can 'e ver& confusing in its simplicit& and power. The e*amples in this section will not 'e
enough in themselves for the reader to o'tain recursive enlightenment. The goal of this section is to
provide an introduction to the concept on recursion. The simple e*amples here, which are used
introduce recursion, are meant to help demonstrate the form and structure for recursion. Iore comple*
e*amples 3than will 'e discussed here4 should 'e studied and implemented in order to ensure a
complete appreciation for the power of recursion.
The calling process previousl& descri'ed supports recursion without an& changes.
+ recursive routine must have a recursive definition that includes#
1. 'ase case, or cases, that provide a simple result 3that defines when the recursion should stop4.
2. rule, or set of rules, that reduce toward the 'ase case.
This recursive definition is referred to as a recursive relation.
19.1 +ecursi)e 'ubroutines
+ recursive su'routine declaration must 'e preceded '& the (e&word recursive. /or e*ample#
recursive subroutine <name> ( <arguments> )
<declarations>
<body of subroutine>
return
end subroutine <name>
=ased on this declaration the su'routine can call itself. The routine must ensure that it eventuall& stops
calling itself. +rguments are passed in the standard wa&.
The calling routine does not need an& special declarations in order to call a recursive routine.
11
:hapter 1B K )ecursion
19. +ecursi)e Print 2inary ,xam"le
This section provides an e*ample recursive su'routine to accept a decimal num'er and print that
num'er in 'inar& 3i.e., using 17s and 074.
-t is assumed the reader has a 'asic understanding of 'inar&
11
representation. This information is
summari?ed in the chapter on :omputer <rgani?ation. +dditionall&, there are man& references
availa'le on the -nternet.
17.2.1 9n'erstan' the Problem
/or this e*ample, the pro'lem is divided into two parts, the main program and the recursive su'routine.
The main program will handle the prompting and reading of the decimal num'er including error
chec(ing and re6prompting as needed. The recursive su'routine will displa& the 'inar& value. $ince
the error chec(ing is alread& performed, the recursive su'routine will assume valid input. /or more
comple* e*amples, the routine ma& need to perform 'asic error chec(ing.
17.2.2 Create the 4lgorithm
<ne 'asic algorithm to convert a decimal num'er into a 'inar& num'er, is successive integer division
'& 2. /or e*ample, given the num'er 1, 1 divided '& 2 is D with a remainder of 1. Ne*t, the D is
divided '& 2 giving with a remainder of 0. +gain, the is divided '& 2 providing a 1 with a
remainder of 1. The final 1 is divided '& 2 resulting in a 0 with a remainder of 1. 8ith a final result of
0, the algorithm is completed. The process is shown as follows#
1!
2
= , remainder 1
,
2
= ! remainder 0
!
2
= 1 remainder 1
1
2
= 0 remainder 1
The remainders, alwa&s 0 or 1, represent the 'inar& value. However, the resulting remainders are
generated in 'ac(wards order. +s such, the resulting remainders 1, 0, 1, and 1 in this e*ample must 'e
reversed for a final value of 1101
2
3as noted in chapter 24.
This process can 'e converted into a recursive relation as follows#
print3inary(n) =
if n1 n
if n>1 print3inary (n/ 2)
output mod(num; 2)
11 /or more information regarding 'inar& representation, refer to# http#55en.wi(ipedia.org5wi(i5=inar&Rnum'er
11!
:hapter 1B M )ecursion
This definition assumes that the value of n is positive. The recursive relation can 'e used '& directl&
converting the algorithm into code.
17.2.3 De6elop the Program
=ased on the recursive definition, a simple recursive su'routine can 'e developed. -n order to
demonstrate the recursive su'routine, a main program is provided that will read a decimal value from
user and ensure it is 'etween 0 and 1,000,000, and then call the recursive routine.
! Simple recursive program to print a decimal number in binary
program binary
implicit none
integer :: decimalNumber
write (*,'(a/)') "Decimal to Binary Conversion Example"
do
write (*,'(a)', advance="no") &
"Enter Decimal Number (0 - 1,000,000): "
read(*,*) decimalNumber
if (decimalNumber >= 0 .and. &
decimalNumber <= 1000000) exit
write (*,'(a)') "Error, decimal value out of range."
write (*,'(a)') "Please re-enter."
end do
write(*,'(/a, i7, a)', advance="no") &
"The decimal value of ", decimalNumber, " is "
call printBinary(decimalNumber)
write (*,'(/)')
contains
! ************************************************************
! Print binary subroutine.
recursive subroutine printBinary(num)
integer, intent(in) :: num
integer :: i
if (num > 1) call printBinary(num/2)
write(*,'(i1)', advance="no") mod(num,2)
return
end subroutine printBinary
111
:hapter 1B K )ecursion
! ************************************************************
end program binary
The spacing and indentation is not re@uired, 'ut helps to ma(e the program more easil& reada'le. The
main program ensures that the recursive routine is not called in invalid values 3i.e., values 04.
17.2.4 0est:Debug the Program
/or this pro'lem, the testing would involve e*ecuting the program and entering a series of decimal
values and ensure that the results are correct. The 8indows calculator provides simple convert6to6
'inar& function that can 'e used for verification.
-f the the program does not provide the correct results, the input to the recursive su'routine should 'e
verified 3via write statements4. Ne*t, some additional write statements in the recursive su'routine can
'e added to provide insight into what is 'eing done for each call.
19.! +ecursi)e Functions
+ recursive function declaration must 'e preceded '& the (e&word recursive. -n addition, the (e&word
resu*t must 'e e*plicitl& added to the function declaration. The resu*t (e&word is used to specif& a
single varia'le for the return value. $imilar to a standard function, the result varia'le must 'e set to a
return value to the calling routine.
The function t&pe specifies the t&pe of the result varia'le. /or e*ample#
<type> recursive function <name> (<arg's>) result (<variable>)
<declarations>
<body of function>
<variable> = expression
return
end function <name>
The main does not need an& special declarations.
19.$ +ecursi)e Factorial ,xam"le
This section provides an e*ample recursive function to computer the mathematical factorial
12
function.
-t is assumed the reader is familiar with the factorial function.
12 /or more information regarding factorial, refer to# http#55en.wi(ipedia.org5wi(i5/actorial
11D
:hapter 1B M )ecursion
17.4.1 9n'erstan' the Problem
The factorial function is mathematicall& defined as follows#
n! =
1=1
n
1
<r more familiarl&, &ou might see 1\ as#
n! = ' 4 ! 2 1
/or this e*ample, the pro'lem is divided into two parts, the main program and the recursive function.
The main program will handle the prompting and reading of the n value. This will include error
chec(ing and re6prompting as needed. The recursive function will compute and return the factorial
value. $ince the error chec(ing is performed performed, the recursive function will assume valid input.
/or more comple* e*amples, the function itself ma& need to perform the error chec(ing. +s such, a
simple helper function could 'e used to verif& the input value or values 'efore calling the recursive
function.
17.4.2 Create the 4lgorithm
+ t&pical recursive relation for factorial is as follows#
factorial( n) =
1 if n=0
n factorial( n1) if n1
This definition assumes that the value of n is positive.
-t must 'e noted that this function could easil& 'e computed with a loop. However, the reason this is
done recursivel& is to provide a simple e*ample of how a recursive function is developed using a
familiar mathematical function.
17.4.3 De6elop the Program
=ased on the recursive definition, a simple recursive function can 'e developed. -n order to
demonstrate the recursive function, a main program is provided that will read the decimal value from
user and ensure it is 'etween 1 and 11, and then call the recursive routine.
The recursive function declaration uses an input argument, n, and a result argument, ans, in this
e*ample. The input argument must 'e declared as intentDinE in the standard manner. However, the
result argument is an out '& definition and will assume the t&pe of the function itself, integer in this
e*ample.
/or the recursive factorial function, the 'asic algorithm is provided as part of the recursive definition.
The e*ample main will read the n value from the user, call the factorial function, and displa& the
results.
! Simple recursive function example.
program recursionExample
implicit none
11A
:hapter 1B K )ecursion
integer :: num, numFact
write (*,'(a/)') "Recursion Example"
do
write (*,'(a)', advance="no") "Enter N (1-15): "
read(*,*) num
if (num >= 1 .and. num <= 15) exit
write (*,'(a)') "Error, N out of range."
write (*,'(a)') "Please re-enter."
end do
numFact = fact(num)
write (*,'(a, i2, a, i10,/)') "Factorial of ", num, &
" is ", numFact
contains
! *************************************************************
! Factorial function
integer recursive function fact(n) result (ans)
implicit none
integer, intent(in) :: n
if (n == 1) then
ans = 1
else
ans = n * fact(n-1)
end if
return
end function fact
! *************************************************************
end program recursionExample
The spacing and indentation is not re@uired, 'ut helps to ma(e the program more easil& reada'le. The
main program ensures that the recursive routine is not called in invalid values 3i.e., values 04.
17.4.4 0est:Debug the Program
/or this pro'lem, the testing would involve e*ecuting the program, entering a num'er, and ensuring
that the result is correct. The 8indows calculator includes a factorial function which can 'e used to
verif& the result.
-f the the program does not provide the correct result, the input to the recursive function should 'e
verified 3via write statements4. Ne*t, some additional write statements in the recursive function can 'e
added to provide insight into what is 'eing done for each call.
11B
:hapter 1B M )ecursion
19.5 +ecursi)e Factorial Function Call Tree
-n order to 'etter understand recursion, a recursion tree can help show how the recursive calls interact.
8hen the initial call to factorial function occurs from main, the main will start into the fact67 function
3shown as step 14. $ince the argument of 1 is not a 'ase case, the fact67 function must call fact67 again
with the argument of n)1 or ! in this e*ample 3step 24. +nd, again, since ! is not the 'ase case, the
fact67 function must call fact67 again with the argument of n61 or in this e*ample 3step 4.
This process continues until the argument passed into the fact67 function meets the 'ase case which is
when the arguments is e@ual to 1 3shown as step 14. 8hen this occurs, onl& then is a return value
provided to the previous call 3step D4. This return argument is then used to calculate the previous
multiplication which is 2 times 1 which will return a value to the previous call 3as shown in step A4.
This process will continue 3steps B, 0, and 104 until the main has a final answer.
$ince the code 'eing e*ecuted is the same, each instance of the fact67 function is different from an&
other instance onl& in the arguments and an& local values 3none in this e*ample4.
110
Illustration 2: Factorial 1ecursion 3ree
fact#
1 Y fact3!4
fact#
! Y fact34
fact#
Y fact324
main#
f U fact314
fact#
2 Y fact314
fact#
return 1
$tep 1
$tep 2
$tep
$tep !
$tep 1
$tep D
$tep A
$tep B
$tep 0
$tep 10
:hapter 1B K )ecursion
-t should also 'e noted that the height of the recursion tree is directl& associated with the amount of
memor& used '& the recursive function. /or pro'lems where the recursion tree is ver& large, this can
have a negative impact on overall performance of a recursive routine.
19.0 ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
17.&.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hat are the two re@uirements for a recursive definitionN
24 -n recursion, the case for which a solution is o'tained directl& is called whatN
4 8hat (e&word is re@uired for a recursive su'routineN
!4 8hat two (e&words are re@uired for a recursive functionN
14 8hat special re@uirements are re@uired of the calling routine in order to call a recursive
su'routine or recursive functionN
D4 /or a recursive routine, what would happen if the routine does not stop recursingN
A4 :reate a recursion tree for the recursive /i'onnaci function 3as descri'ed in the following
suggested proEects section4 with the input of 1. *ote, the recursive /i'onnaci function re@uires
two recursive calls for for the non6'ase case step.
17.&.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 T&pe in the print 'inar& main program and recursive su'routine. Test on several data sets and
verif& that the program produces the correct results.
24 T&pe in the factorial main program and recursive funciton. Test on several data sets and verif&
that the program produces the correct results.
4 The recursive definition of /i'onnaci function is as follows#
fib(n) =
1 if n=0
1 if n=1
fib( n1)+fib(n2) if n2
:reate a main program to read the n value from the user and ensure it is 'etween 1 and !0.
;evelop recursive function, fi', to recursivel& compute the /i'onnaci num'er 'ased on the
provided definition. *ote, the recursive /i'onnaci function re@uires two recursive calls for for
the non6'ase case step.
1D0
:hapter 1B M )ecursion
!4 ;evelop a recursive su'routine to recursivel& print a star tree. =ased on an initial value, n, the
star tree should 'e displa&ed. /or e*ample, for an n value of 1, the program should output
something similar to the following#
Recursive Subroutine Program
Enter Number of Stars: 5
Star Tree:
* * * * *
* * * *
* * *
* *
*
:reate a main program to read the n value from the user and ensure it is 'etween 1 and 10.
;evelop recursive su'routine, print'tars67, to recursivel& print the start tree as shown. The
su'routine should print one line per call. /or successive recursive calls, the n value passed as
an argument should 'e decremented. The 'ased case would 'e one 314 star.
14 8rite a program using a recursive function to determine the num'er of possi'le paths through a
two6dimensional grid. The onl& allowed moves are one step to the right or one step down. /or
e*ample, given a grid as follows#
0 1 2
0
start
1
2
end
Ioving from the starting location, 30,04 in this e*ample, going to the end location, 3,24 in this
e*ample, can 'e performed in 10 different wa&s. Two, of the ten, different wa&s are shown in
the e*ample a'ove. The function must 'e recursive.
:reate a main program to read the initial grid coordinates and ensure that the& are valid
3positive values4 and that the end coordinates are greater than the start coordinates. :reate a
recursive function, count"aths67, to determine the num'er of possi'le paths through a two6
dimensional grid. The function will accept a start coordinate 3row,col4 and a final end
coordinate 3row,col4.
1D1
:hapter 1B K )ecursion
D4 The Tower of Hanoi is a mathematical pu??le that consists of three pegs, and a num'er of dis(s
of different si?es which can slide onto an& peg. The pu??le starts with the dis(s neatl& stac(ed
in order of si?e on one peg, the smallest at the top, thus ma(ing a conical shape.
The o'Eective of the pu??le is to move the entire stac(
to another peg, o'e&ing the following rules#
<nl& one dis( ma& 'e moved at a time.
Each move consists of ta(ing the upper dis( from
one of the pegs and sliding it onto another peg, on
top of the other dis(s that ma& alread& 'e present
on that peg.
No dis( ma& 'e placed on top of a smaller dis(.
The following is a recursive definition for the pro'lem#
hanoi ( n; from; to ; by) =
write(move the disc =romfrom to to) if n=1
hanoi ( n1, from; by ; to) if n>1
hanoi (1, from; to ; by)
hanoi (n1, by ; to ; from)
:reate a main program to read and validate the num'er of dis(s, n, from the user and ensure it
is 'etween 1 and 10. ;evelop recursive function, hanoi, to recursivel& compute a solution to
the Tower of Hanoi pro'lem.
1D2
19 Character 'tring 8 >umeric Con)ersions
:haracters string values, such as ,122 can not 'e used to perform numeric operations such as addition
or multiplication. +s such, for more comple* programs, there is sometimes the need to convert
'etween a character string representing a numeric value and an actual real or integer num'er.
These conversions can 'e performed using what is referred to as an internal read or an internal write.
=asicall&, the read or write functions and associated format statements can 'e used to perform 'asic
conversions. -nstead of reading from an open file, the read and write operations can read and write
directl& from and to varia'les. The specified format provides guidance for the conversion result.
=ased on the input, a conversion ma& not 'e possi'le. /or e*ample, the character string ,.1!2 can 'e
converted into the real value of .1!. However, the character string ,.1?!2 could not 'e converted
since the 7?7 is not a legal numeric value.
-f a conversion is not possi'le, an error would 'e generated. -f not handled, such an error would crash
the program. -n order to address and handle an& potential errors, the iostat parameter for the read5write
operation is used as previousl& descri'ed in the file operations chapter.
19.1 Character 'tring to >umeric Con)ersion
+ character string can 'e converted into an integer or real value using an internal read operation. The
string is provided as the input instead of a file unit num'er. The numeric varia'le is provided as the
location for the result of the read operation. The format will provide guidance for the conversion.
The following is a simple e*ample that will declare two strings and convert the first into an integer
value and the second into a real value. +dditionall&, a third string conversion is perform on a invalid
numeric string 3to 'etter show the error handling4.
! Example program to use an internal read for
! character / numeric conversion.
program cvtExample 1
implicit none
integer :: cvtErr
character(4) :: iString = "1234"
character(7) :: rString = "3.14159"
character(7) :: badString = "3.14z59"
integer :: iNum1, iNum2
real :: pi, tau
write (*,'(a, /)') "Example Conversion Program."
1D
:hapter 10 K :haracter $tring 5 Numeric :onversions
! ----------
! Convert string to an integer value.
read (iString, '(i10)', iostat=cvtErr) iNum1
if (cvtErr == 0 ) then
iNum2 = iNum1 * 2
write (*,'(a, i5, /, a, i5, /)') &
"num1 = ", iNum1, "num2 = ", iNum2
else
write (*,'(a, /)') "Error, invalid integer string."
end if
! ----------
! Convert string to an real value.
read (rString, '(f17.6)', iostat=cvtErr) pi
if (cvtErr == 0 ) then
tau = pi * 2.0
write (*,'(a, f5.3, /, a, f5.3, /)') &
"pi = ", pi, "tau = ", tau
else
write (*,'(a, /)') "Error, invalid real string."
end if
! ----------
! Convert string to an real value.
read (badString, '(f12.4)', iostat=cvtErr) pi
if (cvtErr == 0 ) then
tau = pi * 2.0
write (*,'(a, f5.3, /, a, f6.3)') &
"pi = ", pi, "tau = ", tau
else
write (*,'(a, /)') "Error, invalid real string."
end if
end program cvtExample1
The specific formats used on the read operations in the e*ample are wider or larger than the e*pected
num'er 3which is allowed4. $hould a smaller format 'e used, it would either truncate the value or
possi'l& generate a conversion error. To ensure appropriate conversion, the final values should 'e
verified against the e*pected result.
1D!
:hapter 10 M :haracter $tring 5 Numeric :onversions
+n e*ample of the output for this program is as follows#
Example Conversion Program.
num1 = 1234
num2 = 2468
pi = 3.142
tau = 6.283
Error, invalid real string.
The multiplication '& 2 for each of the numeric values was performed onl& as an e*ample since
multiplication can onl& 'e performed on numeric data t&pes 3i.e., integer, real, or comple*4.
19. >umeric to Character 'tring Con)ersion
+n integer or real value can 'e converted into a character string using a write operation. The string is
provided as the output varia'le instead of a file unit num'er. The numeric varia'le is provided as the
input for the write operation.
The following is a simple e*ample that will convert an integer into a string and a real into a string.
$ome numeric operations are performed on the numeric values and then the resulting strings are
concatenated with another string. :oncatenation can onl& 'e performed on character data t&pes.
! Example program to use an internal write for
! character / numeric conversion.
program cvtExample2
implicit none
integer :: cvtErr
character(50) :: str1, str2, msg1, msg2
integer :: iNum=2468
real :: pi = 3.14, tau
write (*,'(a, /)') "Example Conversion Program."
! ----------
! Convert integer value to a string.
iNum = iNum / 100
write (str1, '(i3)', iostat=cvtErr) iNum
if (cvtErr == 0 ) then
msg1 = "My age is " // str1
write (*,'(a, a)') &
"Message 1 = ", msg1
else
write (*,'(a, /)') "Error, invalid conversion."
end if
1D1
:hapter 10 K :haracter $tring 5 Numeric :onversions
! ----------
! Convert real value to a string.
tau = pi * 2.0
write (str2, '(f5.3)', iostat=cvtErr) tau
if (cvtErr == 0 ) then
msg2 = "The value of TAU is " // str2
write (*,'(a, a, /)') &
"Message 2 = ", msg2
else
write (*,'(a, /)') "Error, invalid conversion."
end if
end program cvtExample2
+n e*ample of the output for this program is as follows#
Example Conversion Program.
Message 1 = My age is 124
Message 2 = The value of TAU is 6.283
<nce the numeric values are converted into strings, the character functions and character operations
can 'e used as needed.
19.! ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
1;.3.1 Quiz Questions
=elow are some @ui? @uestions.
14 8hich operation, internal read or internal write, is re@uired to convert a character string
containing a numeric valueN
24 8hich operation, internal read or internal write, is re@uired to convert a real value into a
character stringN
4 .rovide an appropriate statement to convert the character string sNumU,122 into an integer
varia'le iNum. The error status should 'e written to the varia'le cvt<rr. "ou ma& assume all
varia'les are alread& declared and initiali?ed.
!4 .rovide an appropriate statement to convert the integer varia'le iNumU2! into a character string
sNum. The error status should 'e written to the varia'le cvt<rr. "ou ma& assume all varia'les are
alread& declared and initiali?ed.
1DD
:hapter 10 M :haracter $tring 5 Numeric :onversions
1;.3.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 T&pe in the character string to numeric values conversion e*ample program. Update the values
of the character strings with different data and verif& that the program produces the correct
results.
24 Update the program from the previous @uestion to read a series of character strings from the
user, attempt conversion for each character string to a real value. -f invalid, the user should 'e
re6prompted. -f valid, the sum of the values should 'e maintained. 8hen the user enters a 0 ,
the program should stop reading num'ers, displa& the final sum, and terminate.
4 T&pe in the numeric values to character string values conversion e*ample program. Update the
values of the real and integer values with different num'ers and verif& that the program
produces the correct results.
!4 ;evelop a program to read a series of integer values, sum the values, and convert the final sum
into a character string. The string should 'e concatenated with the string ,The sum is 2 and
displa&ed to the terminal using a single character string varia'le.
14 8rite a program to prompt the user for an integer num'er 'etween 100 and 000, re6prompting
until a valid num'er is provided. 8hen a valid num'er is provided, create a file name in the
form of ,fileZnum'er[.t*t2, open5create the file, and write all num'ers from 1 to the num'er,
one per line, and close the file. /or e*ample, if !2 is entered, the file =i*e42.t+t should 'e
created and contain the num'ers 1, 2, , b, !2 3one per line4.
1DA
:hapter 10 K :haracter $tring 5 Numeric :onversions
1DB
< 'ystem 'er)ices
The term s&stem services generall& refers to as(ing the operating s&stem for information.
The read, write, and file operations 3open, read, write, close4 are common s&stem services and have
alread& 'een addressed in a previous chapter.
<ther s&stem services include o'taining the date and5or time from the operating s&stem and o'taining
the command line arguments 3if an&4. The term command line arguments is used to refer to
information entered on the command line after the program name. This allows the user to provide
some information to the program 'efore it starts 3or as the program is started4, which might save time
as compared to prompting for and interactivel& reading the information at run6time.
8hile there are man& s&stem services, onl& these 'asic ones are presented for reference. These s&stem
services ma& 'e useful when wor(ing on more comple* pro'lems. +dditionall&, the calls and usage for
other s&stem services is ver& similar to how these are performed.
<.1 #ate and Time
The date and time functions are com'ined into a single s&stem service call. The date and time values
can 'e o'tained as character strings, as integers, or 'oth simultaneousl&. The options for date and time
as e*plained in the ne*t section followed '& an e*ample.
-t must 'e noted that if the operating s&stem has an incorrect date or time, the values returned to the
program will also 'e incorrect.
2<.1.1 Date an' 0ime !ptions
The date and5or time values are are o'tained from the operating s&stem using the get_date_time()
s&stem service call. The argument or arguments for the s&stem service call must specif& at least one of
the following options#
date U Zcharacter3B4[
time U Zcharacter3104[
one U Zcharacter314[
va*ues U Zinteger values arra&[
+s noted, each option must provide a location of where to place the results of the specified si?e and
date t&pe. The options are comma separated, similar to the read and write calls noted in a previous
chapter. +t least one argument must 'e included in the call.
The ?one, or time ?one, option will provide the time difference 'etween local time and :oordinated
Universal Time 3UT:
1
4. The character string will provide a result in hours:minutes format and the integer
values will 'e in minutes onl&. However, the minutes can 'e easil& converted to hours.
1 /or more information regarding coordinated universal time, refer to#
http#55en.wi(ipedia.org5wi(i5:oordinatedRUniversalRTime
1D0
:hapter 20 K $&stem $ervices
The options and associated values returned as more full& descri'ed in the following ta'le.
Option Data 4ype Description
date character3B4 The string returned will 'e in the form
""""II;;, where """" is &ear, II is
month, and ;; is date.
time character3104 The string returned will 'e in the form
HHII$$.$$$ where HH is hour, II is
minute, $$ is second, and $$$ is
milliseconds.
one character314 The string returned will 'e in the form of
dHHII, where HHII is the time
difference 'etween local time and
:oordination Universal Time.
va*ues integer arra&, B
elements
The values will 'e returned in the B value
integer arra& as follows#
values314 Q &ear
values324 Q month 316124
values34 Q date 31614
values3!4 Q month 316124
values314 Q hour 30624
values3D4 Q time ?one difference
3minutes4
values3A4 Q seconds 306104
values3B4 Q milleseconds 3060004
Each argument is optional, 'ut at least one argument must 'e included. Iultiple arguments are
allowed.
2<.1.2 Date an' 0ime "#ample Program
The following as an e*ample program that o'tains the date and time information from the operating
s&stem in various formats. The final results are shown for reference.
! Example program to obtain the date and time from the system.
program timeDateExample
! ----------
! Declarations.
implicit none
1A0
:hapter 20 M $&stem $ervices
integer, dimension(8) :: valuesArr
character(len=8) :: today
character(len=10) :: now
character(len=5) :: myzone
integer :: i
! ----------
! Display simple header.
write (*,'(a)') &
"Example Program for Date and Time Functions."
! ----------
! Get date, time, and zone from system as characters.
! Display to screen for reference.
call date_and_time(date=today)
write (*,'(/a, a)') "Today is: ", today
call date_and_time(time=now, zone=myzone)
write (*,'(a, a)') "Time is: ", now
write (*,'(a, a/)') "Time Zone is: ", myzone
! ----------
! Get all date values from the system as integers.
! Display to screen for reference.
call date_and_time(values=valuesArr)
write (*,'(a)') "Values Array:"
write (*,'(a, i4)') "Date, Year: ", valuesArr(1)
write (*,'(a, i2)') "Date, Month: ", valuesArr(2)
write (*,'(a, i2)') "Date, Day: ", valuesArr(3)
write (*,'(a, i2)') "Time, Hour: ", valuesArr(5)
write (*,'(a, i2)') "Time, Minutes: ", valuesArr(6)
write (*,'(a, i2)') "Time, Seconds: ", valuesArr(7)
write (*,'(a, i3)') "Time, Millseconds: ", valuesArr(8)
write (*,'(/,a, i8)') &
"Time difference with UTC in minutes: ", &
valuesArr(4)
write (*,'(a, i2, a1, i2.2 ,/)') &
"Time difference with UTC in hours: ", &
valuesArr(4)/60, ":", mod(valuesArr(4), 60)
end program timeDateExample
1A1
:hapter 20 K $&stem $ervices
8hile this program does not reall& use the time or date values for an&thing meaningful, it does provide
an e*ample of how the information is o'tained for use in other, more comple* programs. The output of
the this e*ample program is shown as follows#
Today is: 20131212
Time is: 154032.491
Time Zone is: -0800
Values Array:
Date, Year: 2013
Date, Month: 12
Date, Day: 12
Time, Hour: 15
Time, Minutes: 40
Time, Seconds: 32
Time, Millseconds: 491
Time difference with UTC in minutes: -480
Time difference with UTC in hours: -8:00
The UT: for 9as Fegas, Nevada is indeed, 6B hours as shown. The results for the UT: will 'e 'ased
on the actual geographic location of where the s&stem e*ecuting the program is located.
<. Command Line %rguments
The usage of command line arguments, information entered on the command line after the program
name, can 'e ver& useful in specific circumstances. =& allowing the user to provide some information
on the command line, it saves the effort of entering the information interactivel& after the program
starts. The term command line arguments is sometimes referred to as command line options.
/or e*ample, when starting a /ortran program for a simple game, the persons name could 'e provided
on the command line. -f the name is provided, the program could use that name. <therwise, the
program could use a generic name such as 7pla&er7. The command line might appears as follows#
c:\fortran> tictactoe ed
<n Uni* 'ased s&stems, this might 'e#
% ./tictactoe ed
8here tictactoe is the name if the program and 7ed7 is the single command line argument.
Iultiple command line arguments can 'e provided, 'ut must 'e separated with a space or multiple
spaces. There is no predefined re@uired format. The formatting or ordering re@uirements are up to the
program.
The gfortran compiler re@uires command line arguments for the various options include the input file
name 3i.e., tictactoe.f014 and the output file name 3i.e., 6o tictactoe4 specification. /or e*ample,
c:\fortran> gfortran tictactoe.f95 -o tictactoe
/or the gfortran compiler, there is no re@uired order for the command line arguments. However, a
valid output file name must follow the 76o7 argument.
1A2
:hapter 20 M $&stem $ervices
The error handling for command line arguments is t&picall& handled differentl&. Ian& programs chec(
the command line arguments, and if incorrect for an& reason, displa& an error message and terminate
the program. This is what the gfortran compiler does when invalid or incorrect arguments are
provided.
-t would 'e possi'le to create a program that could verif& arguments, and if incorrect, displa& an error
message and then re@uest correct input from the user. The handling of the command line arguments
processing is entirel& the responsi'ilit& of the program and not the operating s&stem.
2<.2.1 4rgument Count
There are generall& two steps to o'taining the command line arguments. The first step is getting the
argument count or the num'er of arguments entered on the command line. The previous tic9tac9toe
e*ample has one argument 3i.e., 7ed74. The previous gfortran e*ample had three 3i.e., 7tictactoe.f017, 76o7,
and 7tictactoe74.
The argument count is o'tained using the command_argument_count() s&stem service as follows#
integer :: myCount
myCount = command_argument_count()
8hich will return the count in the varia'le my%ount 3as shown a'ove4. The count will 'e ?ero if no
arguments are entered.
2<.2.2 >et 4rguments
<nce the argument count is availa'le, the actual arguments can 'e o'tained. The arguments are alwa&s
returned as character values. -f the argument is meant to 'e used as a real or integer value, it must 'e
converted. The :haracter $tring 5 Numeric :onversions chapter provides a description of how this can
'e accomplished.
8hen o'taining the command line arguments, the get_command_argument() s&stem service is
used. +n argument is returned into a specified character varia'le. The character varia'le should 'e
large enough 3i.e., a'le to hold enough characters4 to store the e*pected argument. The actual length of
the returned argument can optionall& 'e provided. +dditionall&, if the character varia'le is too small,
the returned result will 'e truncated and the status set accordingl& to indicate an error.
The options and associated values returned are descri'ed in the following ta'le.
Option Data 4ype Description
*ength integer -nput integer argument indicating which
argument should 'e returned. Iust 'e
'etween 1 and the
commandLargumentLcountDE value.
va*ue character3Y4 <utput character varia'le of where to store
the N
th
argument as specified '& the length
value 3a'ove4. The varia'le must 'e
declared with an appropriate si?e.
1A
:hapter 20 K $&stem $ervices
*ength integer <utput integer argument for the actual
length of the string returned '& the value
argument 3a'ove4.
status integer <utput integer argument for the returned
status value. + return status value of 0 is
success and 61 is fail.
The first two arguments are re@uired and the final two arguments are optional.
2<.2.3 Comman' .ine 4rguments8 "#ample Program
This simple e*ample o'tains the command line argument count and displa&s the arguments to the
screen for reference. -n this e*ample, the program will e*pect a real value as the first argument and an
integer value as the second argument 3if a second argument is provided4. +n& additional arguments,
while not used, are still displa&ed the screen along with the argument count value.
/or this e*ample, since the num'er of arguments is un(nown ahead of time, an arra& to hold the
arguments is allocated at run6time. 8hile this is not necessar&, it does help provide a more complete
e*ample. $uch a process would onl& 'e appropriate if a var&ing num'er of command line arguments is
desired.
! Example program to demonstrate how to obtain the
! command line arguments from the system.
program argsExample
implicit none
integer :: argCount, allocStatus, rdErr, i, iNum
real :: rNum
character(len=80), dimension(:), allocatable :: args
! ----------
! Get command line argument count from system.
argCount = command_argument_count()
if (argCount == 0) then
write (*,'(a)') "No command line arguments provided."
stop
end if
! ----------
! Allocate an array to hold the arguments.
allocate(args(argCount), stat=allocStatus)
1A!
:hapter 20 M $&stem $ervices
if (allocStatus > 0) then
write (*,'(a)') &
"Allocation error, program terminated."
stop
end if
! ----------
! Get each argument, one at a time, from system.
do i = 1, argCount
call get_command_argument(number=i,value=args(i))
end do
! ----------
! Display arguments to screen.
if (argCount == 0) then
write (*,'(a)') "No command line arguments provided."
else
if (argCount == 1) then
write (*,'(a, i1, a)') "There was ", &
argCount, " command line argument."
else
write (*,'(a, i2, a)') "There were ", &
argCount, " command line arguments."
end if
write (*,'(/,a)') "The arguments were: "
do i = 1, argCount
write (*,'(a, a)') " ", trim(args(i))
end do
write (*,*)
end if
! ----------
! Convert a string to a numeric value using an internal read.
if (argCount >= 1) then
read (args(1), '(f12.5)', iostat=rdErr) rNum
if (rdErr == 0 ) then
write (*,'(a, f12.5)') &
"Argument 1 - Real Number = ", rNum
else
write (*,'(a)') "Error, invalid real value."
end if
end if
if (argCount >= 2) then
1A1
:hapter 20 K $&stem $ervices
read (args(2), '(i10)', iostat=rdErr) iNum
if (rdErr == 0 ) then
write (*,'(a, i10)') &
"Argument 2 - Integer Number = ", iNum
else
write (*,'(a)') "Error, invalid integer value."
end if
end if
write (*,*)
end program argsExample
+n e*ample of the output for this program with valid command line arguments provided is shown
'elow. The e*ecuta'le name of the e*ample program is 7args7.
c:\fortran> args 3.14 23 hello world
There were 4 command line arguments.
The arguments were:
3.14
23
hello
world
Argument 1 - Real Number = 3.14000
Argument 2 - Integer Number = 23
c:\fortran>
+nother e*ample of the output for this program with invalid command line arguments provided is
shown as follows#
c:\fortran> args 3.14 23 hello world
There were 4 command line arguments.
The arguments were:
hello
3.14
23
world
Error, invalid real value.
Error, invalid integer value.
c:\fortran>
*ote, the order for the valid and invalid arguments was chosen ar'itraril&.
1AD
:hapter 20 M $&stem $ervices
<.! ,xercises
=elow are some @ui? @uestions and proEect suggestions 'ased on this chapter.
2<.3.1 Quiz Questions
=elow are some @ui? @uestions.
14 :an the date alone 'e o'tained 3i.e., without o'taining the time4 using the getLdateLtimeDE
s&stem service 3&es5no4N
24 8hen using the getLdateLtimeDE s&stem service to o'tain the integer date and time values, what
is the inde* num'er for the#
1. The month value.
2. The hour value.
. The &ear value.
4 How can the integer time ?one value 'e converted to hours:minutes formatN
!4 .rovide the getLdateLtimeDE s&stem service call to o'tain the current date string into the alread&
declared character varia'le d'tr.
14 .rovide the getLdateLtimeDE s&stem service call to o'tain the current time string and time ?one
string into the alread& declared character varia'les time'tr and zone'tr.
D4 .rovide the getLdateLtimeDE s&stem service call to o'tain the current date5time integer values,
and the current date string into the alread& declared B element integer values&rr arra&.
A4 -f there are no arguments entered on the command line, what is returned '& the
getLcommandLargumentDE s&stem serviceN
B4 .rovide an appropriate statement to o'tain the
rd
command line argument, the argument length, and
a status value. "ou ma& assume the varia'les for the command line argument 3character4, named
args, the length 3integer4, named arg3length, and the status 3integer4, named, arg3stat are alread&
declared appropriatel&.
2<.3.2 uggeste' Pro(ects
=elow are some suggested proEects.
14 T&pe in the get date and time e*ample program. Update the output to more clearl& displa& onl&
the current date and time on one line. )emoval the unnecessar& or redundant output.
24 T&pe in the get command line arguments e*ample program. E*ecute the program using a
variet& of different e*pected and une*pected arguments.
1AA
:hapter 20 K $&stem $ervices
4 ;evelop a program that e*pects command line arguments for a title and time 3hours and
minutes4. :alculate and displa& the difference 'etween the current time and the time from the
command line. -f the command line arguments are incomplete or incorrect, an error message
should 'e displa&ed and the program, terminated. The program should use 2!6hour format.
<ne possi'le approach to determining the time difference would 'e to convert each time into
minutes 3from hours and minutes format4, compute the difference, and convert the difference in
minutes 'ac( to hours and minutes format. The final output should displa& the title, the s&stem
time, the entered time, and the time difference. +ll times should 'e displa&ed in hours:minutes
format.
!4 8rite a program to get the date from the s&stem and displa& a formatted date. The formatted
date should 'e# Zda& of wee([, Zmonth name[ Zdate[, Z&ear[. /or e*ample, 12525201
should 'e displa&ed as 2onday, Decem3er 2, 201!. Each string should include onl& the
appropriate spacing. $pecificall&, there should 'e no e*tra spaces 'etween the words or
num'ers 3including the date value, 2 in the e*ample4.
To calculate the da& on which a particular date falls, the following algorithm ma& 'e used.
*ote, all varia'les are integers and the divisions are integer divisions.
a =
14 month
12
y = year a
m = month + 12 a 2
daynum = date + y +
y
4
y
100
+
y
400
+
(
!1
m
12
)
mod $
8here the month, date, and year varia'les are the integer date values 312, 2, and 201 in the
previous e*ample4. The final value of daynum is 0 for a $unda&, 1 for a Ionda&, 2 for a
Tuesda&, and so forth with the ma*imum value of D for $aturda&.
14 Update the program from the previous @uestion to write the formatted date to a file. The file
name should 'e created 'ased on the current date in the following format
,fileZII;;""[.t*t2 /or e*ample, for a date of 125025201, the file should 'e named
=i*e12021!.t+t and contain the character string 2onday, Decem3er 2, 201!.
D4 8rite a program to o'tain the current date and attempt to open a file 'ased on the date in the
following format, ,fileZII;;""[.t*t2. /or e*ample, for a date of 125025201, the file
should 'e named =i*e12021!.t+t. -f the file e*ists, the contents should 'e displa&ed to the
screen. -f the file does not e*ist, an appropriate error message should 'e displa&ed.
1AB
1 %""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.
!2 M ,4 N &,
J !! 1 ,' a &$
O !4 ) ,, 3 &.
P !' C ,$ c &&
Q !, D ,. d 100
R !$ E ,& e 101
S !. % $0 = 102
T !& " $1 g 10!
D 40 C $2 h 104
E 41 I $! i 10'
B 42 J $4 U 10,
A 4! < $' ? 10$
, 44 / $, * 10.
9 4' 2 $$ m 10&
. 4, 6 $. n 110
0 4$ O $& o 111
0 4. - .0 p 112
1 4& ; .1 H 11!
2 '0 5 .2 r 114
! '1 # .! s 11'
4 '2 4 .4 t 11,
' '! : .' u 11$
, '4 V ., v 11.
$ '' 7 .$ 8 11&
. ', K .. + 120
& '$ V .& y 121
W '. I &0 122
X '& Y &1 Z 12!
G ,0 [ &2 \ 124
@ ,1 ] &! ^ 12'
F ,2 _ &4 ` 12,
a ,! L &' 12$
1A0
:hapter 21 K +ppendi* + C +$:-- Ta'le
1B0
%""endix 2 1 Windo*s 'tart=7" 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 Fista, 8indows A, and 8indows B.
The 'asic process is ver& similar to I+: and 9inu* 3which is not covered here4.
.1 Wor/ing Files
=efore wor(ing with /ortran program files, &ou should decide where &ou will 'e wor(ing 3:e# drive,
U$= 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 /ortran 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 U$= drive.
. &btaining The Com"iler
/irst, &ou will need to download and install the GNU /ortran compiler. The main we' page for the
GNU /ortran compiler is#
http://gcc.gnu.org/fortran/
This page provides general information regarding the /ortran compiler development effort, proEect
o'Eectives, and current status.
Iore specific information, and the 8indows compiler 'inaries, can 'e found on the g/ortran 8i(i
page, which is located at#
http://gcc.gnu.org/wiki/GFortran
This page contains lin(s to the Gfortran 'inaries. <n this page, clic( on the lin( la'eled#
)inaries =or 7indo8s, /inu+, and 2acO#
8hich will displa& the page for the GNU=inaries for various platforms, including 8indows, Iac<$,
and 9inu*. :lic( on the 8indows lin(, which will show the various 8indows options. /or standard
8indows 3J.5Fista5A5B4, the heading 2in"7 3ui*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 Fista, 8indows J.,
8indows A and 8indows B.
+fter downloading, install the compiler. The installation can 'e accomplished '& dou'le6clic(ing on
the downloaded file. +s with all 8indows installs, it will re@uire $&stem +dministrator privileges.
1B1
:hapter 22 K +ppendi* = C 8indows $tart6Up -nstructions
.! 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&.
22.3.1 ?in'o+s @P:)ista:2
-n /or 8indows A, the ,:ommand .rompt2 is usuall& under -rograms Q 1ccessories Q Command
-rompt.
22.3.2 ?in'o+s 7
/or 8indows B, the ,:ommand .rompt2 can 'e found '& using $earch and is listed under the
7indo8s #ystem heading.
22.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.
22.3.4 De6ice 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. /irst, esta'lish the device of the wor(ing
director&. -f the files are on :#e 3the main hard drive4, the device is alread& set. -f the wor(ing
director& is located on a networ( drive, alternate drive, or U$= drive, the device will need to 'e set.
Using 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. /or e*ample, if &our device is <, &ou would
t&pe ,?W2.
+t the ,G#e[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. /or e*ample, if the director& is named cs11A, the
command would 'e ,cd cs11$2.
1B2
:hapter 22 M +ppendi* = C 8indows $tart6Up -nstructions
/or 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 2y Computer listing.
.$ 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 /ortran compiler is not installed. The installation issue must 'e addressed 'efore
continuing. <nce the installation is completed successfull&, the compilation steps detailed in :hapter
can 'e completed.
.5 Com"ilation
<nce the /ortran 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 @ualifier 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.
.0 ,xecuting
To e*ecute or run a program, t&pe the name of the e*ecuta'le file. /or e*ample, to e*ecute or run the
1B
:hapter 22 K +ppendi* = C 8indows $tart6Up -nstructions
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.
.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.
1B!
! %""endix C 1 +andom >umber -eneration
Generating random num'ers is a common re@uirement for man& pro'lems. The following provides a
summar& of utili?ing the 'uilt6in /ortran random num'er generator routines.
!.1 Initiali(ation
The first step in generating random num'ers is to initiali?e the /ortran 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 re@uest a random num'er, a real varia'le must 'e declared and then passed to the following call to
the 'uilt6in randomRnum'er34 routine. /or 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. /or e*ample, to
simulating the roll of a dice, a random integer num'er 'etween 1 and D would 'e re@uired. The
following code would o'tain the random num'er and then scale it and convert to integer as re@uired.
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. /urther, since .000 is the largest possi'le value 3since 1.0 is
not4, and .000 Y D will generate D 31.0 truncated to 1 with 1 added4.
1B1
:hapter 2 K +ppendi* : C )andom Num'er Generation
!.! ,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.
1BD
:hapter 2 M +ppendi* : C )andom Num'er Generation
!.$ ,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.
The following e*ample simulates the roll of two dice, which re@uires two random integer num'ers,
each 'etween 1 and D.
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. /or 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
1BA
:hapter 2 K +ppendi* : C )andom Num'er Generation
C:\fortran> dice
Dice 1: 1
Dice 2: 6
Dice Sum 7
C:\fortran>
The dice values will 'e different for each e*ecution.
1BB
$ %""endix # 1 Intrinsic Functions
The following is a partial listing of the /ortran 01 intrinsic functions. <nl& the most common intrinsic
functions are included in this section. + complete list can 'e found on6line at the GNU /ortran
documentation we' page.
$.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.
%unction Description
-NT3+4 )eturns integer value of real argument +, truncating 3real
part4 towards ?ero.
N-NT3J4 )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 +.
$. Integer Functions
The following ta'le provides a list of intrinsic functions that can 'e used for integers.
%unction Description
+=$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.
1B0
:hapter 2! K +ppendi* ; C -ntrinsic /unctions
$.! +eal Functions
The following ta'le provides a list of intrinsic functions that can 'e used for reals.
%unction Description
+=$3+4 )eturns real a'solute value of real argument +.
+:<$384 )eturns real inverse cosine of real argument 8 in radians.
+$-N384 )eturns real inverse sine of real argument 8 in radians.
+T+N3J4 )eturns real inverse tangent of real argument J in radians.
:<$384 )eturns real cosine of real argument 8 in radians.
9<G384 )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.
$-N384 )eturns real sine of real argument 8 in radians.
$>)T384 )eturns real s@uare root of real argument 8. )eal
argument 8 must 'e positive.
T+N3J4 )eturns real tangent of real argument J in radians.
$.$ Character Functions
The following ta'le provides a list of intrinsic functions that can 'e used for characters5strings.
%unction Description
+:H+)3-4 )eturns the character represented '& integer argument -
'ased on the +$:-- ta'le 3+ppendi* +4. -nteger argument -
must 'e 'etween 1 and 12A.
-+:H+)3:4 )eturns the integer value of the character argument :
represented '& +$:-- ta'le 3+ppendi* +4.
9EN3$T)4 )eturns an integer value representing the length of string
argument $T).
9ENRT)-I3$T)4 )eturns an integer value representing the length of string
argument $T) e*cluding an& trailing spaces.
9GE3$T)1,$T)24 )eturns logical true, if $T)1 f $T)2 and false otherwise.
9GT3$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.
100
:hapter 2! M +ppendi* ; C -ntrinsic /unctions
$.5 Com"lex Functions
The following ta'le provides a list of intrinsic functions that can 'e used for comple* num'ers.
%unction Description
+-I+G3W4 )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.
$.0 %rray Functions
The following ta'le provides a list of intrinsic functions that can 'e used for arra&s.
%unction Description
I+J9<:3+14 )eturns integer location or inde* of the ma*imum value in
arra& +1.
I+JF+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-N9<:3+14 )eturns integer location or inde* of the minimum value in
arra& +1.
I-NF+93+14 )eturns minimum value in arra& +1. T&pe of value
returned is 'ased on the t&pe of the argument arra& +1.
$UI3+14 )eturns sum of values in arra& +1. T&pe of value returned
is 'ased on the t&pe of the argument arra& +1.
101
:hapter 2! K +ppendi* ; C -ntrinsic /unctions
$.5 'ystem Information Functions
The following ta'le provides a list of intrinsic functions that o'tain information from the s&stem.
%unction Description
:<II+N;R+)GUIEN
TR:<UNT34
)eturns the num'er of command line arguments.
GETR:<II+N;R+)G
UINENT3NUI=E),
F+9UE, 9ENGTH,
$T+TU$4
)eturns command line arguments, if an&.
NUI=E), integer argument of the num'er to
return. Iust 'e 'etween 1 and
:<II+N;R+)GUIENTR:<UNT34.
F+9UE, character3Y4, N
th
argument
9ENGTH, integer, length of argument returned in
F+9UE
$T+TU$, integer, status, 0Usuccess and 61UF+9UE
character arra& is too small for argument, other
valuesUretrieval failed
:.URT-IE3T-IE4 )eturns the amount of :.U time e*pended on the current
program in seconds. T-IE is return as a real value.
;+TER+N;RT-IE
3;+TE,
T-IE,W<NE,F+9UE$4
)eturn date and time.
;+TE34, character3B4, 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<NE34, character314, string in the form of
dHHII, where HHII is the time difference
'etween local time and :oordination Universal
Time.
F+9UE$34, integer arra& where
F+9UE$314 Q &ear
F+9UE$324 Q month 316124
F+9UE$34 Q date 31614
F+9UE$3!4 Q month 316124
F+9UE$314 Q hour 30624
F+9UE$3D4 Q Time ?one difference 3minutes4
F+9UE$3A4 Q seconds 306104
F+9UE$3B4 Q milleseconds 3060004
Each argument is optional, 'ut at least one argument must
'e included.
102
5 %""endix , 1 3isuali(ation *ith ->7"lot
The /ortran language does not have an& 'uilt6in graphics capa'ilities. To support some 'asic data
visuali?ation a plotting application, GNUplot, can 'e used. GNUplot 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 GNUplot 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.
5.1 &btaining ->7"lot
The first step is to o'tain and install GNUplot.
GNUplot is availa'le at,
http://www.gnuplot.info/
To ensure that GNUplot is installed correctl&, for 8indows machine, &ou can enter command prompt
and t&pe,
wgnuplot
which will start GNUplot '& 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 GNUplot.
5. Formatting Plot Files
$ince our specific use of GNUplot will involve plotting a data file created with a /ortran program, it
will 'e necessar& to provide some information and directions for GNUplot 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.
10
:hapter 21 K +ppendi* E C Fisuali?ation with GNUplot
2-.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.
2-.2.2 %ooter
The footer is used to formall& tell GNUplot 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
Nothing after the footer will 'e read '& GNUplot.
5.! 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 GNUplot and instruct GNUplot to read the file ,file.plt2. The file name can 'e
an&thing and the file e*tension is not re@uired 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.
5.$ ,xam"le
This section provides an e*ample program that plots a simple function.
y = sin( x)
(
1cos( x)
!.0
)
The program, data file, and final output are presented for reference.
10!
:hapter 21 M +ppendi* E C Fisuali?ation with GNUplot
2-.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.
101
:hapter 21 K +ppendi* E C Fisuali?ation with GNUplot
2-.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&.
2-.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.
10D
0 %""endix F 1 ?ui( ?uestion %ns*ers
This appendi* provides answers for the @ui? @uestions in each chapter.
0.1 ?ui( ?uestion %ns*ers4 Cha"ter 1
There are no @ui? @uestions in :hapter 1.
0. ?ui( ?uestion %ns*ers4 Cha"ter
>ui? @uestion answers for chapter 2 are as follows#
14 -n the computer, information is represented in 'inar&.
24 :onvert the /ortran program into 'inar& or machine language.
4 The =U$ connects the memor& to the :.U.
!4 The answer are as follows#
a4 The 'inar& value 0000101
2
is 1 in decimal.
'4 The 'inar& value 0001001
2
is 0 in decimal.
c4 The 'inar& value 0001101
2
is 1 in decimal.
d4 The 'inar& value 0010101
2
is 21 in decimal.
14 :haracters are represented in 'inar& using 'inar& +$:--. )efer to +ppendi* + for the +$:--
ta'le.
D4 .rograms are stored on the the primar& storage device 3$$;, dis( drive, or other storage
media4.
A4 .rogram must 'e in )+I in order to e*ecute.
0.! ?ui( ?uestion %ns*ers4 Cha"ter !
>ui? @uestion answers for chapter are as follows#
14 The input file for the compiler is the /ortran program file.
24 The output from the compiler is the e*ecuta'le program.
4 /ortran programs must start with the program GnameF statement and end with the end
program GnameF statement.
!4 :omments are mar(ed with the e*planation point 3J4.
14 The t&pical file e*tension for a /ortran 00501 program is ,.=&'2.
D4 The t&pical file e*tension of the compiler output file is ,.e+e2 for 8indows and no e*tension for
Uni* 'ased machines 3i.e., I+: and U'untu4.
10A
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
0.$ ?ui( ?uestion %ns*ers4 Cha"ter $
>ui? @uestion answers for chapter ! are as follows#
14 The five /ortran data t&pes are integer, rea*, character, *ogica*, and comp*e+.
24 + /ortran varia'le name must start with a letter. Faria'le names ma& include num'ers, 'ut
must start with a letter.
4 The implied data t&pes are integer, real, integer, real, and real.
!4 The statements are#
integer :: value
real :: count
14 The statements are#
real :: rate = 7.5
D4 The statements are#
real, parameter :: e = 2.71828183
0.5 ?ui( ?uestion %ns*ers4 Cha"ter 5
>ui? @uestion answers for chapter 1 are as follows#
14 The assignment operator is @ 3e@ual sign4.
24 The e*ponentiation operator is BB 3dou'le asteris(s, no space4.
4 +n integer varia'le can 'e converted to a real with the real conversion function. /or e*ample,
realVar = real(intVar)
!4 +n integer varia'le can 'e converted to a real with the real conversion function. /or e*ample,
intVar = int(realVar)
*ote, in this e*ample precision ma& 'e lost since the fractional part is truncated 3not rounded4.
14 The two logical constants are .true. and .=a*se. which must include the leading and trailing
periods.
D4 $ome intrinsic functions are rea*DE, intDE, nintDE, cosDE, sinDE, modDE, tanDE, and sHrtDE. There
are more as listed in +ppendi* ;.
A4 The statements are as follows#
x1 = (pi / 6.0) * (3.0 * a**2 + 3.0 * b**2 + c**2)
x2 = -(2.0 * a / c) * cos(b) * sin(b)
x3 = -b + sqrt(b**2 4.0 * a * c) / (2.0 * a)
10B
:hapter 2D M +ppendi* / C >ui? >uestion +nswers
0.0 ?ui( ?uestion %ns*ers4 Cha"ter 0
>ui? @uestion answers for chapter D are as follows#
14 The ,(*,*)2 means to send it to the screen in 7free format7.
24 The statement is as follows#
write (*,*) "Programming is Fun!"
4 The statements are as follows#
integer :: myage
write (*,*) "Enter Age:"
read (*,*) myrage
0.5 ?ui( ?uestion %ns*ers4 Cha"ter 5
>ui? @uestion answers for chapter A are as follows#
14 The four program development steps are
1. Understand the .ro'lem
2. :reate the +lgorithm
. ;evelop the .rogram
!. Test5;e'ug the .rogram
24 The three t&pes of errors are compiler error, run6time error, and logic error.
4 $ince the formula is incorrect, that would 'e a logic error.
!4 + compiler error is generated when the compiler does not understand the statement. This often
occurs when statements are mis6spelled. /or e*ample,
writte(*,*) "Opps"
would generate a compiler error since 8rite is mis6spelled.
0.9 ?ui( ?uestion %ns*ers4 Cha"ter 9
>ui? @uestion answers for chapter B are as follows#
14 The si* relational operators are F, F@, G, G@, @@, and 0@.
24 The three 'asic logical operators are .and., .or., and .not. where the leading and trailing periods
are re@uired.
4 The answers are .true., .true., .=a*se., .true., .true., .=a*se., and .true. where the leading and
trailing periods are re@uired.
100
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
!4 The statements are as follows#
if (lives <= 0) then
write (*,*) "Game Over"
end if
*ote, this also could 'e done as follows#
if (lives <= 0) write (*,*) "Game Over"
14 The statements are as follows#
if (num < 0) then
num = abs(num)
write (*,*) "Nnum was made positive"
end if
D4 The statements are as follows#
if (y /= 0) then
z = x / y
else
z = 0
write (*,*) "Z not calculated"
end if
*ote, another correct solution is as follows#
if (y == 0) then
z = 0
write (*,*) "Z not calculated"
else
z = x / y
end if
A4 The statements are as follows#
if (x <= 0.0) then
f = x**2 * y
else
f = x * y
end if
0.9 ?ui( ?uestion %ns*ers4 Cha"ter 9
>ui? @uestion answers for chapter 0 are as follows#
14 8hen an exit statement is e*ecuted, the current loop will 'e e*ited, thus not completing an&
remaining iterations.
24 There ma& 'e an unlimited num'er of e*it statements. T&picall&, there is onl& one.
200
:hapter 2D M +ppendi* / C >ui? >uestion +nswers
4 8hen a continue statement is e*ecuted, the remaining statements in the loop are s(ipped and
the ne*t iteration of the loop is started 3from the 'eginning of the loop4.
!4 There ma& 'e an unlimited num'er of continue statements. T&picall&, there is onl& one.
14 -f there are multiple continue statements, onl& the first e*ecuted continue statement will 'e
e*ecuted.
D4 The output is as follows#
The SUM is: 15
A4 The output is as follows#
start
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
end
B4 The statements are valid, however since the initial value of i is greater than the stop value, no
statements in the loop will 'e e*ecuted.
04 The statements are valid, however since the initial value of i is greater than the stop value, no
statements in the loop will 'e e*ecuted.
104 There is no specified limit.
114 8hen nesting -/ statements, the nested -/ statement must 'e completel& nested within the loop.
0.1< ?ui( ?uestion %ns*ers4 Cha"ter 1<
>ui? @uestion answers for chapter 10 are as follows#
14 The format specifiers are rIw, r%w.d, r/w, nK, 0, and r1.
24 The output, using an ,R2 3underscore4 for 'lan(s, is as follows#
Hello
Hello World
4 The output, using an ,R2 3underscore4 for 'lan(s, is as follows#
005
!4 The statement is as follows#
write (*,'(i3)') num1
201
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
14 The statement is as follows#
write (*,'(f7.5)') pi
D4 The statement is as follows#
write (*,'(a,/,a)') "Programming", "Is Fun!"
A4 The statement is as follows#
write (*,'(a)', advance="no") "Enter Number:"
0.11 ?ui( ?uestion %ns*ers4 Cha"ter 11
>ui? @uestion answers for chapter 11 are as follows#
14 The declaration is as follows#
character (len=12) :: msg = "Hello World!"
24 The results are .=a*se., .true., .=a*se., .=a*se., .=a*se., .=a*se., .true. where the leading and trailing
periods are re@uired.
4 The value for astr1 U ,a'c2, the value for astr2 U ,!1D2, the value for astr U ,12!1DAB0102,
and the value for astr! U ,;E/12'c2.
!4 The integer value can 'e o'tained '& using the -+:H+)34 function.
14 The character can 'e o'tained from the integer value '& using the +:H+)34 function.
0.1 ?ui( ?uestion %ns*ers4 Cha"ter 1
>ui? @uestion answers for chapter 12 are as follows#
14 =efore a file can 'e read or written, it must 'e opened.
24 The recommended range for a file unit num'er is 'etween 10 and 00 3inclusive4.
4 The answers as as follows#
a4 The name of the file is =i*e.t+t.
'4 The unit num'er used is 14.
c4 "es, the error message will 'e printed if the file does not e*ist.
d4 -f the status varia'le, opnstat, is [ 0, an error on the file open has occurred.
!4 The read statement is as follows#
read(20,'(13x,i2,8x,i3,8x,i5)') num1, num2, num3
202
:hapter 2D M +ppendi* / C >ui? >uestion +nswers
0.1! ?ui( ?uestion %ns*ers4 Cha"ter 1!
>ui? @uestion answers for chapter 1 are as follows#
14 +n arra& is considered a direct access structure since an& arra& value can 'e directl& accessed
3without accessing an& other locations4.
24 "es, an arra& can hold integer values.
4 "es, arra& can hold real values.
!4 The declarations are as follows#
integer, parameter :: SIZE1 = 100
real, dimension(10) :: rvalues
integer, dimension(SIZE1) :: inums
real, dimension(0:9) :: counts
14 The answers as as follows#
a4 10.
'4 21.
c4 20.
d4 20.
D4 +n arra& can 'e allocated a compile6time or run6time 3'ut not 'oth4.
A4 The answers as as follows#
a4 The arra& will contain the following values#
nums
1 1
2 00
! 00
1 0
'4 The statements is called an implied do loop.
c4 The statement will displa& the first 1 values on one line as follows#
__1_99__3_99__0
20
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
0.1$ ?ui( ?uestion %ns*ers4 Cha"ter 1$
>ui? @uestion answers for chapter 1! are as follows#
14 No, a multi6dimensional arra& can hold either real values or integers values.
24 The answer is a.
4 The answers are as follows#
a4 11.
'4 The arra& contains the following values#
1 2
1 2.0 .0 !.0
2 .0 !.0 1.0
!.0 1.0 D.0
! 1.0 D.0 A.0
1 D.0 A.0 B.0
c4 .0.
d4 !.0
e4 A.0
!4 +n unsuccessful allocation can 'e detected '& chec(ing the status varia'le for a value [ 0.
0.15 ?ui( ?uestion %ns*ers4 Cha"ter 15
>ui? @uestion answers for chapter 11 are as follows#
14 The two t&pes of /ortran su'programs are su'routines and functions.
24 + function returns a single value.
4 The varia'les in the call are referred to as actual arguments.
!4 The varia'les in the function heading are referred to formal arguments.
14 The return t&pe is integer.
D4 "es, it possi'le to pass integer arguments to a real function.
A4 The (e&word contains.
B4 The answers are as follows#
a4 B.
'4 0.
20!
:hapter 2D M +ppendi* / C >ui? >uestion +nswers
04 The answers are as follows#
a4 "es.
'4 No.
c4 10.0.
104 The term 'ariable scope refers to where a given varia'le can 'e accessed.
114 The answers are as follows#
a4 in
'4 out
c4 inout
124 The term side6effect is when a function changes one or more of its input arguments. -n general,
this is consider poor practice and should 'e avoided.
0.10 ?ui( ?uestion %ns*ers4 Cha"ter 10
>ui? @uestion answers for chapter 1D are as follows#
14 +n item in a derived data t&pe is referred to as a component.
24 :omponents in a derived data t&pe are accessed with the R.
4 The definition is as follows#
type circle
character(20) :: name
real :: radius
integer :: x, y, x
end type circle
!4 The declaration is as follows#
type(circle) :: ring1, ring2
14 The definition is as follows#
type planet
character(15) :: name
real :: radius, volume
end type planet
type(planet) :: earth, mars
201
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
D4 The definition is as follows#
type date
character(10) :: monthname
integer :: month, date, year
end type date
A4 The answers are as follows#
a4 The statements are as follows#
type(date) :: today
today%monthname = "December"
today%month = 12
today%date = 25
today%year = 2013
'4 The statements are as follows#
type(date) :: newyear
newyear%monthname = "January"
newyear%month = 1
newyear%date = 1
newyear%year = 2011
0.15 ?ui( ?uestion %ns*ers4 Cha"ter 15
>ui? @uestion answers for chapter 1A are as follows#
14 The primar& purpose for using a module is to allow the program to 'e split into multiple source
files.
24 The use Gmodu*e6ameF statement must 'e used in the main program.
4 The modu*e Gmodu*e6ameF statement must 'e used in the main program.
!4 <nl& one main program is allowed.
14 +n unlimited num'er of modules is allowed.
D4 "es, the contains statement is re@uired in the module.
0.19 ?ui( ?uestion %ns*ers4 Cha"ter 19
>ui? @uestion answers for chapter 1B are as follows#
14 The two re@uirements for a recursive definition are a 'ase case and rule, or set of rules, that
reduce toward the 'ase case.
24 -n recursion, the case for which a solution is o'tained directl& is called the 'ase case.
20D
:hapter 2D M +ppendi* / C >ui? >uestion +nswers
4 The (e&word recursive is re@uired for a recursive su'routine.
!4 The two (e&words re@uired for a recursive function are recursive and resu*t.
14 There are no special re@uirements needed in the calling routine in order to call a recursive
su'routine or recursive function.
D4 -f a a recursive routine does not stop recursing, it will recurse indefinitel&, thus hanging the
program and producing no results. The program would need to 'e manuall& terminated.
A4 + complete recursion tree for the recursive /i'onnaci function with an input of ! is as follows#
20A
step 1
step 2
step
step !
step 1
step D step A
step B
step 0
step 10
step 11
step A
5ib6
return -
5ib6
5ib(-) 7
5ib(.)
5ib6
return -
5ib6
return .
5ib6
return -
5ib6
return .
5ib6
5ib(0) 7
5ib(-)
5ib6
5ib(-) 7
5ib(.)
5ib6
5ib(/) 7
5ib(0)
main6
5ib(2)
step 12
step 1
step 1!
step 11
step 1D
:hapter 2D K +ppendi* / C >ui? >uestion +nswers
0.19 ?ui( ?uestion %ns*ers4 Cha"ter 19
>ui? @uestion answers for chapter 10 are as follows#
14 +n internal read is re@uired to convert an character string contain a numeric value.
24 +n internal "rite is re@uired to convert an real value into a character string.
4 The statement to convert the character string sNumU,122 into an integer varia'le iNum is as
follows#
read (sNum, '()', iostat-cvtErr) iNum
!4 The statement to convert the integer varia'le iNumU2! into a character string sNum is as
follows#
write (sNum, '()', iostat=cvtErr) iNum
0.< ?ui( ?uestion %ns*ers4 Cha"ter <
>ui? @uestion answers for chapter 20 are as follows#
14 "es, the date alone 'e o'tained 3i.e., without o'taining the time4 using the getRdateRtime34
s&stem service.
24 The answers are as follows#
a4 2.
'4 1.
c4 1.
4 The hours can o'tained from the minutes '& dividing '& D0 and the minutes o'tained '&
mod3hours,D04.
!4 The statement is as follows#
call get_date_time(date=dStr)
14 The statement is as follows#
call get_date_time(time=timeStr, zone=zoneStr)
D4 The statement is as follows#
call get_date_time(values=valuesArr)
A4 -f there are no arguments entered on the command line, the getLcommandLargumentDE s&stem
service call will return a 0.
B4 The statement is as follows#
call get_command_argument(number=3, value=arg3, &
length=arg3length, status=arg3stat)
20B
5 %""endix - 1 Fortran 95 @ey*ords
-n programming, a (e&word is a word or identifier that has a special /ortran 01 meaning. Ge&words are
reserved in that the& can not 'e used for an&thing else such varia'le names.
The =ype 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.
/or reference, 'elow is a partial list of (e&words or reserved words. /or a complete list of (e&words,
refer to the on6line GNU /ortran 01 documentation.
<ey8ord 4ype 2eaning
a**ocata3*e attri'ute no space allocated here later allocate
a**ocate statement allocate memor& space now for varia'le
assignment attri'ute means su'routine is assignment 3U4
3ac?space statement 'ac( up one record
ca** statement call a su'routine
case statement used in select case structure
character statement intrinsic data t&pe
c*ose statement close a file
comp*e+ statement intrinsic data t&pe
contains 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*se construct part of if, else if, else, end if
e*se i= construct part of if, else if, else, end if
e*se8here construct part of where, elsewhere, end where
end do construct ends do loop
end =unction construct ends function
200
:hapter 2A K +ppendi* G C /ortran 01 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 se*ect construct ends select case
end su3routine construct ends su'routine
end type construct ends t&pe
end 8here 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
intrinsic statement sa&s that following names are intrinsic
inHuire statement get the status of a unit
?ind 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*ist 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
210
:hapter 2A M +ppendi* G C /ortran 01 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
pu3*ic statement and
attri'ute
in a module 6 visi'le outside
read statement performs input
rea* statement intrinsic data t&pe
recursive attri'ute allows functions and derived t&pe recursion
resu*t attri'ute allows naming of function result
return statement returns from e*its su'routine or function
re8ind statement move read or write position to 'eginning
se*ect case construct start of a case construct
stop statement terminate e*ecution of the main procedure
su3routine 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
use statement 'rings in a module
8here construct conditional assignment
8hi*e construct a while form of a do loop
8rite statement performs output
211
:hapter 2A K +ppendi* G C /ortran 01 Ge&words
212
Index
+=$3+4.........................................................1B0p.
+ccessing +rra& Elements.........................0A, 100
+ccessing :omponents...................................12
+:H+)3-4.................................................B2, 100
+:<$384........................................................100
+ctual arguments.............................................11B
+ddition.............................................................21
+dvance clause..................................................A
+-I+G3W4......................................................101
+llocate.............................................................0A
+merican $tandard :ode for -nformation
-nterchange..........................................................1
+rgument count...............................................1A
+rgument -ntent...............................................11B
+rgument .assing............................................110
+rguments.......................................................11B
+rra& ;eclaration......................................01, 10A
+$:--..................................................................1
+$-N384.........................................................100
+ssignment........................................................21
+T+N3J4.........................................................100
=ase 10................................................................!
=ase 2..................................................................1
=inar& digit..........................................................1
=inar& Num'ers..................................................1
=it........................................................................1
=oolean..............................................................1
=&te.....................................................................1
:all statement..................................................11B
:+$E statement................................................!0
:entral .rocessing Unit.......................................
:haos Game......................................................0!
:haracter...........................................................1
:haracter constant.............................................20
:haracter 9iterals..............................................20
:haracter )epresentation....................................1
:haracter $tring 5 Numeric :onversions.........1D
:I.9J3J,"4..................................................101
:ommand line arguments........................1D0, 1A2
:ommand line options.....................................1A2
:ommandRargumentRcount34..........................1A
:<II+N;R+)GUIENTR:<UNT34........102
:ompiler..............................................................!
:ompiler Error..................................................A
:ompiling............................................................B
:omple* constant..............................................20
:omple* 9iterals...............................................20
:omple* num'er...............................................1
:omponent......................................................11
:omputer program..............................................2
:onditional :ontrolled 9ooping.......................D1
:onditionall& :ontrolled 9oop E*ample..........D
:onstant.............................................................11
:ontains...........................................................11B
:oordinated Universal Time...........................1D0
:<$384...........................................................100
:ounter :ontrolled E*ample.............................10
:ounter :ontrolled 9ooping.............................1A
:.URT-IE3T-IE4.........................................102
:&cle statement.................................................10
;ate.................................................................1D0
;+TER+N;RT-IE........................................102
;ecimal Num'ers................................................!
;eclaration......................................................12
;eclarations, E*tended $i?e Faria'les..............1D
;efinition........................................................11
;erived ;ata T&pes.........................................11
;irect access structure.......................................01
;iscriminant......................................................!1
;is( drive............................................................
;ivision.............................................................22
;o6loop..............................................................1A
;&namic +rra& +llocation.........................0A, 10B
;&namic +rra& ;eclaration...............................0D
;&namic ;eclaration.......................................10B
E6notation..........................................................10
E@ual to.............................................................!1
Error Terminolog&.............................................A
21
:hapter K -nde*
Escape character..........................................20, A0
E*it statement....................................................10
E*ponentiation...................................................2
E*ternal............................................................11A
E*ternal declaration.........................................11B
E*ternal )outines............................................11B
/actorial function............................................11D
/ile <pen...........................................................BA
/ormal arguments............................................11B
/<)I+T statement..........................................D0
/unctions.........................................................110
GetRcommandRargument34..............................1A
GETR:<II+N;R+)GUINENT3NUI=E),
F+9UE, 9ENGTH, $T+TU$4........................102
GetRdateRtime34...............................................1D0
GNUplot..........................................................10
Greater than.......................................................!1
Greater than or e@ual.........................................!1
Helper function................................................11A
-+:H+)3:4..............................................B2, 100
-/ statement.......................................................!
-/ THEN E9$E -/ statement............................!!
-/ THEN E9$E statement.................................!
-I.9-:-T N<NE..............................................1
-mplicit t&ping...................................................1
-mplied do6loop.................................................0B
-nde*..................................................................01
-NT3+4.............................................................1B0
-nteger................................................................12
-nteger constants................................................10
-nteger 9iterals..................................................10
-ntent3in4..........................................................11B
-ntent3inout4.....................................................11B
-ntent3out4........................................................11B
-nterface 'loc(.................................................11B
-nternal.............................................................11A
-nternal read.....................................................1D
-nternal )outines.............................................11B
-nternal write...................................................1D
-ntrinsic /unctions.....................................2!, 110
-ostat................................................................1D
-rrational num'ers.............................................1
Ge&word....................................................12, 200
Gind................................................................1Dp.
Gind specifier.................................................1Dp.
9ENRT)-I3$T)4.....................................B, 100
9EN3$T)4.................................................B2, 100
9ess than............................................................!1
9ess than or e@ual..............................................!1
9GE3$T)1,$T)24...........................................100
9GT3$T)1,$T)24...........................................100
9iterals...............................................................10
99E3$T)1,$T)24...........................................100
99T3$T)1,$T)24............................................100
9<G384..........................................................100
9ogic Error........................................................0
9ogical...............................................................1
9ogical constant................................................21
9ogical :onstants..............................................21
9ogical <perators..............................................!2
9oop..................................................................1A
Iachine language................................................!
Iagic [email protected]
I+J9<:3+14................................................101
I+JF+93+14................................................101
I-N9<:3+14..................................................101
I-NF+93+14..................................................101
I<;3)1,)24................................................1B0p.
Iodule file......................................................1!A
Iodules...........................................................1!1
Ionte :arlo.....................................................110
Iultidimensional +rra&s.................................10A
Iultiplication....................................................22
N-NT3J4..........................................................1B0
Not e@ual to.......................................................!1
<'Eect file........................................................1!A
<perands............................................................!1
<perating $&stem................................................2
<rder of <perations...........................................2
.arameter...........................................................11
.i estimation....................................................111
.rimar& $torage...................................................
.rint =inar&.....................................................11!
.rogram 9a&out...............................................11A
.rogram $tatement..............................................A
.&thagorean theorem.......................................110
>uadratic e@uation............................................!1
)andom +ccess Iemor&.....................................
)andomRnum'er34...........................................1B1
)andomRseed34................................................1B1
)ational num'ers...............................................1
)ead statement..................................................0
)eal constants....................................................10
)eal 9iterals......................................................10
21!
:hapter M -nde*
)eal num'er2....................................................1
)E+93+4.........................................................101
)ecursion.........................................................11
)ecursive /actorial..........................................11D
)ecursive relation............................................11
)ecursive su'routine.......................................11
)elational e*pression........................................!1
)elational E*pressions......................................!1
)elational <peration..........................................!1
)elational <perator...........................................!1
)elational <perator 3alternate4..........................!1
)esult varia'le.................................................11D
)un6time Error..................................................B
$econdar& source file......................................1!1
$E9E:T :+$E $tatement................................!0
$elector lists......................................................!0
$ide Effects......................................................120
$ide6effect.......................................................120
$-N384............................................................100
$ingle ;imension +rra&s..................................01
$olid $tate ;rive.................................................
$ource file............................................................B
$>)T384.........................................................100
$tatic +rra& ;eclaration....................................0D
$tatic ;eclaration......................................01, 10B
$tring.................................................................20
$tring1...............................................................1
$u'program T&pes...........................................11A
$u'programs....................................................11A
$u'routines......................................................120
$u'script............................................................01
$u'traction........................................................22
$UI3+14.........................................................101
$&stem $ervices...............................................1D0
T+N3J4...........................................................100
Time.................................................................1D0
T)-I3$T)4...............................................B, 100
T&pe :hec(ing...................................................1!
T&pe declaration................................................1!
Unit num'er.......................................................BA
Use $tatement..................................................1!D
User6;efined /unctions..................................120
Using /unctions and $u'routines....................11B
Falues arra&.....................................................1D0
Faria'le )anges.................................................1!
Faria'le $cope.................................................11B
8hole num'er...................................................12
8rite statement..................................................20
Wone.................................................................1D0
.and....................................................................!2
.e@......................................................................!1
.ge......................................................................!1
.gt.......................................................................!1
.le.......................................................................!1
.lt........................................................................!1
.ne......................................................................!1
.not.....................................................................!2
.or.......................................................................!2
5U........................................................................!1
Z.........................................................................!1
ZU......................................................................!1
UU......................................................................!1
[.........................................................................!1
[U......................................................................!1
211