Introduction To Programming Using FORTRAN 95: This Document and All The Examples May Be Found Online at

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

IntroductiontoProgramming

usingFORTRAN95

http://www.fortrantutorial.com/

Theseworksheetsaimtoprovideanintroductionto
programming.ThelanguagechosenforthisisFORTRAN95.This
isbecauseFORTRANisparticularlysuitableforscienceand
engineering;itisalsoverywidelyavailable.

Theskillsyouacquireworkingthroughthesenotescanbe
appliedtoanycomputinglanguage.Theconceptsyouwilllearn
aresharedincommonwitheveryothercomputinglanguage.


Thisdocumentandalltheexamplesmaybefoundonlineat:

http://www.fortrantutorial.com/

JanetANicholson2011

CopyrightJanetANicholson2011 1 fortrantutorial.com
1 THEBASICS..............................................................................................................................................3
1.1 AIMS............................................................................................................................................................3
1.2 INSTALLFTN95PERSONALEDITION....................................................................................................................3
1.3 YOURFIRSTPROGRAMMINGSESSION....................................................................................................................3
1.4 PLATOAPROGRAMMINGENVIRONMENT.............................................................................................................3
1.5 RUNNINGYOURFIRSTFORTRAN95PROGRAM....................................................................................................4
1.6 PROGRAMSTRUCTURE......................................................................................................................................6
1.7 MOREONINPUTANDOUTPUT...........................................................................................................................6
1.8 MOREDATATYPESINTEGERANDCHARACTER......................................................................................................8
1.9 SAVINGTHECONTENTSOFOUTPUTWINDOW......................................................................................................10
2 MAKINGDECISIONS...............................................................................................................................11
2.1 AIMS..........................................................................................................................................................11
2.2 ASSIGNMENT................................................................................................................................................11
2.3 ARITHMETIC.................................................................................................................................................11
2.4 INTRINSICFUNCTIONS.....................................................................................................................................12
2.5 MAKINGDECISIONS.......................................................................................................................................13
2.6 PROGRAMSTYLE...........................................................................................................................................14
2.7 MOREONDECISIONMAKING............................................................................................................................14
2.8 OTHERLOGICALOPERATORS.............................................................................................................................14
2.9 MULTIPLECONDITIONS...................................................................................................................................15
2.10 THESIMPLEIFSTATEMENT..........................................................................................................................15
2.11 IMPORTANTNOTETESTINGFORZERO..........................................................................................................16
3 LOOPS....................................................................................................................................................17
3.1 AIMS..........................................................................................................................................................17
3.2 MIXINGVARIABLETYPES..................................................................................................................................17
3.3 THEDOLOOP................................................................................................................................................18
3.4 NESTEDDOLOOPS........................................................................................................................................19
3.5 USINGLOOPSTODOSUMMATION.....................................................................................................................20
4 USINGFILESANDEXTENDINGPRECISION...............................................................................................22
4.1 AIMS..........................................................................................................................................................22
4.2 READINGFROMFILES......................................................................................................................................22
4.3 WRITINGTOFILES..........................................................................................................................................23
4.4 EXTENDINGTHEPRECISION...............................................................................................................................23
4.5 MAGNITUDELIMITATIONS...............................................................................................................................25
4.6 CONVERGENCEEXITINGLOOPSONACONDITION.................................................................................................25
5 ARRAYSANDFORMATTEDI/O...............................................................................................................27
5.1 AIMS..........................................................................................................................................................27
5.2 ARRAYS.......................................................................................................................................................27
5.3 ARRAYMAGIC...............................................................................................................................................29
5.4 MULTIDIMENSIONALARRAYS...........................................................................................................................30
5.5 FORMATTINGYOUROUTPUT.............................................................................................................................31
5.5.1 IntegerSpecification.......................................................................................................32
5.5.2 FloatingpointSpecification............................................................................................32
5.5.3 ExponentialSpecification................................................................................................32
5.5.4 CharacterSpecification...................................................................................................33
5.6 IMPLIEDDOLOOPTOWRITEARRAYS..................................................................................................................33
6 SUBROUTINESANDFUNCTIONS.............................................................................................................35
6.1 AIMS..........................................................................................................................................................35
6.2 REUSINGCODETHESUBROUTINE...................................................................................................................35
6.3 ARGUMENTSTOSUBROUTINES..........................................................................................................................36
6.4 USERDEFINEDFUNCTIONS..............................................................................................................................38
7 ADVANCEDTOPICS................................................................................................................................40
7.1 AIMS..........................................................................................................................................................40
7.2 ARRAYFUNCTIONS.........................................................................................................................................40
7.3 WRITINGREALPROGRAMSFLOWCHARTS.......................................................................................................42

CopyrightJanetANicholson2011 2 fortrantutorial.com

1 TheBasics
1.1 Aims
Bytheendofthisworksheet,youwillbeableto:
CreateandrunaFORTRAN95program
Understandbasicprogramstructure
Starttodealwithprogrammingerrors
Starttounderstandreal,integerandcharactervariabletypes.
SaveacopyofyouroutputinWord.

1.2 InstallFTN95PersonalEdition
SearchforSilverfrostFTN5personaleditionorclickthislink
http://www.silverfrost.com/32/ftn95/ftn95_personal_edition.aspx.
Downloadandinstallthesoftwareacceptingallthedefaults.

1.3 Yourfirstprogrammingsession

LocateanddoubleclickthePlato icon
ClickFile,New
SelectFreeFormatFortranFile
ClickFile,SaveAs
Createadirectorycalledfortranprogramsandopenit
Typefirst.f95

1.4 Platoaprogrammingenvironment

CopyrightJanetANicholson2011 3 fortrantutorial.com
Platoisa"programmingenvironment".WithinPlato,youcancreateandeditprogramsandgetthem
torun.Plato'seditorisspecialitunderstandsthesyntaxofvariousprogramminglanguages.Wetell
Platowhichlanguageweareusingwhenwecreateouremptyfileandsaveitwitha.f95(FORTRAN
95)extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable
tocheckthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsaboutusinga
colourcodetodistinguishbetweenthevariouselementsofthelanguage.

Alwaysensurethatyourprogramfileshavea.f95extension

1.5 RunningyourfirstFORTRAN95Program

Exercise1.1

Typeinthefollowingexactlyasshown:

!My first program


program first
print *,'This is my first program'
end program first

CopyrightJanetANicholson2011 4 fortrantutorial.com

Clicktheblack,(theExecutebutton).
PlatowillgetFTN95tocheckyourprogramforerrors.Ifitfindsanyproblems,itwillgiveyou
thedetails.Ifyouhavetypedintheprogramexactlyasshownabove,anexecutablefilewill
begenerated(first.exe).Platowillthenautomaticallygettheprogramtostartexecuting.
Abannerwillappearforacoupleofsecondsandwillthendisappear(that"sthepricewe
havetopayforusingthefreesoftware)
Ablackconsolewindowwillappear.
PressReturntoclosethewindow.DonotclicktheXatthetoprightofthewindow.

PlatocangetupsetifyoudonotpressReturntoclosethewindow,trythis

Saveyourprogramfirst!
Runtheprogramagain(click)
ThistimeclicktheXatthetoprightofthewindowtocloseit.
Makeupyourownmindaboutwhichisthebetterwaytoclosethiswindowinfuture!

CopyrightJanetANicholson2011 5 fortrantutorial.com
1.6 ProgramStructure
Examinethefollowingshortprogram:
program sum !a:nameofprogram
!an example of program structure !b:acomment
real :: answer,x,y !c:declarations
print *, 'Enter two numbers' !d:output
read *, x !e:input
read *, y !e:input
answer=x+y !f:arithmetic
print *, 'The total is ', answer !g:output
end program sum !h:endofprogram

Thereareanumberofgeneralpointshere:
Theprogramismadeupofanumberoflines.Eachlineiscalledastatement.
Eachstatementismadeupof
variablenamese.g.answer, x, y
operatorse.g.+,-etc
keywordse.g.read, print
Thestatementsareexecutedsequentially.

Let'sbreaktheprogramdown,linebyline:
a) Thenameoftheprogram.Keepitreasonablyshortandmeaningful.
b) Acommentexplainingthepurposeoftheprogram.Commentsareindicatedbyan
exclamationmark.Alltexttotherightofanexclamationmarkisignoredbythecompiler.
Programmersusecommentstohelpthemrememberhowaprogramworks.Useof
appropriatecommentsinprogramsaidsunderstandingandisgoodpractice.
c) Variablesanswer, x and y areusedtostorefloatingpointnumbersweindicate
thisbydeclaringthemasreal.
d) print *,outputstothescreentheasteriskmeansusethedefaultnumberofdecimal
placeswhenthenumberiswrittentothescreen.
e) Wereadinformationfromthekeyboardandstorethevaluesin xandy.
f) Dosomearithmeticandstoretheanswerinanswer.
g) Outputtheresulttothescreen
h) Concludetheprogram

1.7 MoreonInputandOutput
Exercise1.2
Openanewfileandcallitio.f95.
Typeinthefollowingprogram:
program io
real :: x,y,z
print *, 'enter the values x,y and z'
read *, x,y,z
print *, 'the values you typed are for z,y,x are: ',z,y,x
end program io
Executeitbypressing
YoucanenterthenumbersoneatatimeandpresstheEnterkeyeachtime.
Executetheprogramagain
Thistimetypeallthreenumbersononelineseparatedbycommas.

CopyrightJanetANicholson2011 6 fortrantutorial.com
Lookattheprintstatement
print *, 'the values you typed are for z,y,x are: ',z,y,x
Inthisstatement,weareoutputtingfourseparatethings,aliteralstringofcharacters,
'the values you typed are for z,y,x are: '
andthevariablesz,y,andx.Wemayoutputseveralitemsatonetime,providedtheyareseparated
bycommas.

Exercise1.3
Thefollowingprogramhasanumberoferrors.
Createanewfilecalledbug.f95andthentypeinthefollowingprogramexactlyasshown.
Youcanalsodownloadthisfilefrom
http://fortrantutorial.com/fortrantutorialexampleprograms/index.php
program bug
this program is full of errors
real :: a,b,c
a = b + c
read *,c
print *,a
end program simple
Thecompilerwillreporttwoerrormessageswhenitattemptstocompile.Clickonthedetailsbutton.
Eacherrorgeneratesamessage.


Doubleclickingonthemessagewill
takeyoutothelineintheprogramwherethefaultoccurs.

CopyrightJanetANicholson2011 7 fortrantutorial.com

Correctthetwoerrors.
ClickExecute
Thereisnowonefurthererror,Platowillprovideayellowwarningalert.Watchthescreen
carefully!Thewindowwillcloseandthentheprogramwillstarttoexecute.Somethingis
notcorrecthowevertheprogramwill"hang".Itisactuallywaitingforyoutoinputavalue,
becauseofthelineread*,c.Totheuseroftheprogram,thisisnotatallobviousthey
mayhavethoughtthattheprogramhascrashed!
Typeinanumberthenpressenter
Theprogramreturnsanstrangevalue.Thisisan"executiontime"error.
Weneedtofindoutwhatthewarningmessagewas.Clickthe"compile"button(totheright
ofthebinoculars).Thenclickthe"details"button.Platowilltellyouthatthevariablebhas
notbeengivenavalue.
Correcttheprogramtogivebavalue,andthenexecutetheprogramagain.
Thereisstillaproblem.Thistime,itisaproblemwiththeprogram'slogic.

NeedaHint? Theprogramstatementsareexecutedsequentially.
a=b+c
read *, c
print *, a
Thestatementa=b+cdoesn'tmakesense,asatthisstageoftheprogram,wehaven'tyetgivena
valuetoc.

Importantpointstonote
Therearetwotypesoferrorsassociatedwiththisprogram:compilererrorsandruntime
errors.
Theprogramisalsouserunfriendly.Theprogramwaitsforinputwithouttellingtheuser
whatisneeded.
Fixtheruntimeerrorby:

readinavalueforb
correcttheorderofthestatements
maketheprogrammoreuserfriendly,

thencompareyourprogramwiththeonecalledbugfixed.f95at

http://fortrantutorial.com/fortrantutorialexampleprograms/

1.8 MoreDatatypesintegerandcharacter
Sofar,wehaveonlyusedreal(floatingpointnumbers)inourprograms.Wecanalsospecifythat
numbersareintegerandcharacter.Programconvert,below,demonstratestheiruse.

Withinagivenrange,integersarealwaysrepresentedexactlywhereastheprecisionofrealnumbers
islimitedbythearchitectureofthemachine.Therealvariabletypegivesus6figuredecimal
precision.(Ifthisdoesn'tseemenoughdon'tworrywe'llcomebacklateronwhenweexaminehow
toincreasethenumberofdigitsofprecisioninSection4).

Charactervariablesholdstringsofcharacterslike
'A happy day was had by all'
'Yes'
'N'
'3 + 4 equals 7'

CopyrightJanetANicholson2011 8 fortrantutorial.com
Whenthecharactervariableisdeclared,weshowthemaximumlengththatthestringcanoccupyby
followingthenamebya*thenitsmaximumlength.Theexamplebelowhasamaximumlengthof10
charactersallowedforaperson'snamethismightnotalwaysbeenough!Youhavetomakea
judgementhere.

program convert
!This example shows the use of integer and character variables.
implicit none
integer :: pounds,pence,total
character :: name*10
print *,'What is your name?'
read *,name
print *, 'Hi ',name,'! Enter number of pounds and pence'
read *, pounds,pence
total =100 * pounds + pence
print *,'the total money in pence is ',total
end program convert

NOTEtheinclusionoftheline

implicit none

Byincludingitinyourprogram,FORTRANwillcheckthatyouhaveproperlydeclaredallyourvariable
types.Inthebadolddaysofprogramming,declarationofvariableswasthoughttobeunnecessary
andtheoldFORTRANcompilersusedanimplicitconventionthatintegershavenamesstartingwith
thelettersintherangein,alltheothersbeingreal.FORTRANstillallowsyoutodothisifwedon't
includetheline,implicitnone.Timehasshownthatoneofthecommonestreasonsforerrorina
programistheincorrectuseofvariables.


Alwaysuseimplicitnoneatthestartofeveryprogram.

Exercise1.4
Withtheprogramconvertinsection1.5asaguide,writeaprogramtotestouteverythingyou've
learnedsofar.Youmightincludedifferenttypesofvariables,forexamplereal,integer,and
character.Includeinputandoutputusingreadandprint.Anexamplemightbeaprogramthatasks
peoplequestions,includingthingsliketheirageandnameandsoon.Itcould,forexample,printout
theiryearofbirthwithasuitablemessage.It'suptoyou,justuseyourimagination.

CopyrightJanetANicholson2011 9 fortrantutorial.com

1.9 SavingthecontentsofOutputWindow

Runyourlastprogramagain.Whentheblackoutputwindowopensrightclickonthe
Platoiconinthetopleftcorner

Clickonedit
ClickSelectall
Clickcopy
OpenanewdocumentinWordorNotepadandclickpaste.

CopyrightJanetANicholson2011 10 fortrantutorial.com
2 MakingDecisions
2.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Doarithmetic
StarttouseFORTRANintrinsicfunctions
Begintounderstandprogramflowandlogic
Knowhowtotestforzeroimportant!
Learnmoreaboutgoodprogrammingstyle

2.2 Assignment
Whenwestartprogramming,thesimilaritybetweenmathematicalequationsandFORTRAN
statementscanbeconfusing.
ConsiderthefollowingFORTRANstatements:

x = 2 Storethevalue2inmemorylocationx
y = 3 Storethevalue3inmemorylocationy
z = x + y Addthevaluesstoredinmemorylocation
xandyandstoretheresultinmemorylocationz
Inmathematics,x=2meansthatthevariablexisequalto2.InFORTRANitmeansstorethevalue
2inthememorylocationthatwehavegiventhenamex.

Thesignificanceofthisismadeclearerbythefollowingequationinmathematics:

x+y=z

Inmathematics,thismeansthatthelefthandsideoftheequationisequaltotherighthandside.
InFORTRAN,thisexpressionismeaningless:thereisnomemorylocation"x+y"andsoitwouldleadto
acompilererror.


RuletherecanonlyeverbeONEvariablenameonthelefthandsideofanequalssign

Exercise2.1
Writeaprogramwhichreadsintwonumbersaandb.Gettheprogramtoswapthevaluesaroundso
thatthevaluethatwasinaisnowinb,andprintouttheresult.Hintyouneedtodeclareathird
variableforintermediatestorageofthedata.(Checkyourprogrambyexaminingprogramswap.f95at
http://fortrantutorial.com/fortrantutorialexampleprograms/

2.3 Arithmetic
Thearithmeticoperatorsare
+,- plusandminus
*,/ multiplyanddivide
** exponentiation(raisetothepower)
() brackets
TheorderofprecedenceinFORTRANisidenticaltothatofmathematics.
Unlikealgebra,theoperatormustalwaysbepresentxyisnotthesameasx*y
Whereoperationsareofequalprecedencetheyareevaluatedlefttoright
Consecutiveexponentiationsareevaluatedrighttoleft
Wecanoverridetheorderofevaluationbyuseofbrackets

CopyrightJanetANicholson2011 11 fortrantutorial.com

Exercise2.2
Thefollowingprogramisanexampleoftheuseofarithmetic.
program calculate
implicit none
! a simple calculator
real :: x,y,z,answer
x=1.5
y=2.5
z=3.5
answer=x+y/z
print *,'result is ',answer
end program calculate
Exploretheuseofarithmeticoperatorsbymodifyingprogramcalculate.Useittocalculatethevalues:

x y
1.
xz
2. xyz
z
3. xy

2.4 IntrinsicFunctions
FORTRANisespeciallyusefulformathematicalcomputationbecauseofitsrichlibraryofinbuilt
functions(intrinsicfunctions).Weshallmentionafewbrieflyhere:

functionname typeofargument typeofresult Definition


sin(x) real real sine
cos(x) real real cosine
tan(x) real real tangent
atan(x) real real arctangent
abs(x) real/integer real/integer absolutevalue
sqrt(x) real real squareroot
exp(x) real real ex
log(x) real real log x
10

Trigonometricfunctionsarecalculatedinradians(1radian=180/Pidegrees).

Thereare,ofcourse,manymore,andthislistdoesn'tcoverallFORTRANvariabletypes.Thefollowing
exampleshowstheuseofsomeoftheinbuiltfunctions.

program trig
implicit none
real :: a,pi
print *,'Enter an angle between 0 and 90'
read *, a
pi=4.0*atan(1.0)
print *,'the sine of ',a,' is ',sin(a*pi/180)
end program trig

CopyrightJanetANicholson2011 12 fortrantutorial.com
2.5 MakingDecisions
Sofar,ourprogramshaveworkedaslittlemorethanbasiccalculators.Thepowerofprogramming
comesinwhenwehavetomakedecisions.Copytheexampleprogram,test.f95,toyourownfile
space.Seeifyoucanunderstandwhatisgoingon.
program test
implicit none
!use of a simple menu
real :: x,y,answer
integer :: choice
!set up the menu the user may enter 1, 2 or 3
print *,'Choose an option'
print *,'1 Multiply'
print *,'2 Divide'
print *,'3 Add'
read *,choice
x=3.4
y=2.9
!the following line has 2 consecutive
!equals signs (no spaces in between)
if (choice = = 1) then
answer=x*y
print *,'result = ',answer
end if
if (choice = = 2) then
answer=x/y
print *,'result = ',answer
end if
if (choice = = 3) then
answer=x+y
print *,'result = ',answer
end if
end program test
Theboldedlinesintheaboveprogramarecalledifendifstatements.Theyworklikethis:

if(conditionistrue)then
executethisline
andthis
andsoonuntilwegetto
endif

ItfollowsthatiftheconditionisNOTtruethenthecode'jumps'tothenextstatementfollowingthe
'endif'.Thestatementsbetweentheifandtheendifaredeliberatelyindented,thismakesthe
programeasiertoread.

Weusetwoconsecutiveequalssigns(nospaceinthemiddle)totestforequality.Compare
if (choice == 3) then test
choice = 3 assignment

CopyrightJanetANicholson2011 13 fortrantutorial.com
Exercise2.3
Examineprogramtestabove.Theline

print *,'result = ',answer


isrepeatedseveraltimes.Isthisagoodidea?Canyoumodifytheprogramtomakeitmoreefficient?

2.6 ProgramStyle
Agoodprogram:

Usescommentsappropriatelytoexplainwhatishappening.
Usesindentationtomaketheprogrameasiertoread.
Usesmeaningfulvariablenames.
Usessensiblepromptstolettheuserknowwhatisgoingon.
Usesimplicit noneatthestartofeveryprogram.
Isefficient!

Ifyouwanttogetmaximummarksforyourassignmentskeeptheabovepointsfirmlyinmind.Itis
notenoughjusttogetaprogramtowork!

2.7 Moreondecisionmaking
Inourtest.f95above,therewasaproblemiftheuserenteredavaluethatwasn'tcateredforbythe
program.

Whathappensiftheuserdoesn'tenteroneofthevalues1,2or3?

Wearegoingtolookatanewstructure,calledif,else,endifthathandlesthissituation.Examinethe
followingcodesnippet:

if(choice==1)then
dosomething
elseif(choice==2)then
dosomethingelse
else
dothisifnothingelsesatisfiestheconditions
endif

2.8 Otherlogicaloperators
Sofar,allourtestshavebeenforequality.Thereareseveraltestswecanmake:

== equalto(thereisnospacebetweentheequalssigns)
/= notequalto
< lessthan
<= lessthanorequalto
> greaterthan
>= greaterthanorequalto

CopyrightJanetANicholson2011 14 fortrantutorial.com

2.9 MultipleConditions

Supposeweneedtotestifxisgreaterthanyandyisgreaterthanz.Therearedifferentwaysofdoing
this:

if(x>y)then
if(y>z)then
dosomething
endif
endif

Thiscanalsobehandledbythefollowing:

noticethe.and.
if(x>y.and.y>z)then
dosomething
endif

Ifwewantedtocheckwhetheranumberwerelessthanagivenvalueorgreaterthanagivenvalue
wecouldwrite:

noticethe.or.
if(x<10.or.x>20)then
dosomething
endif

Exercise2.4
Writeaprogramthatreadsanumberfromthekeyboard.Gettheprogramtodecidewhether:

thevalueofthenumberisgreaterthan0butlessthan1
orisgreaterthan1butlessthan10
orisoutsideofboththeseranges

Printoutasuitablemessagetoinformtheuser.

2.10 Thesimpleifstatement
Thereisasimpler,onelineformoftheifstatement.Saywejustwantedtoprintoutasimple
messagesuchas
print *, 'enter a positive number'
read *, num Thissnippetalso
if (num <0) stop introducesauseful,
if (num < 10) print *, 'less than 10' simplestatement
if (num > 10) print *, 'greater than 10' stopitsimply
print *,'It is a positive number' stopstheprogram.

CopyrightJanetANicholson2011 15 fortrantutorial.com
2.11 Importantnotetestingforzero
Supposethatyouwishtotestwhetherarealvariableiszero.Thetest
Makesureyou
if (x = = 0) then . understandthis!

isnotasatisfactorytest.Althoughintegernumbersareheldexactly
bythecomputer,realnumbersarenot.

Thewayaroundthisistotestiftheabsolutevalueofthevariableislessthansomesmallpredefined
value.Forexample:
if (abs(x) < .000001) then
print *,No zero values! Please enter another number
read *, x
end if

CopyrightJanetANicholson2011 16 fortrantutorial.com
3 Loops
3.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Understandmoreabouttheuseofrealandintegervariablesandhowtouseamixtureof
datatypesinexpressions
Understandhowtoreusecodebylooping
Knowhowtocontrolthenumberoftimesasectionofcodeisexecutedbyusingadoloop

3.2 Mixingvariabletypes
Exercise3.1

Copydivide.f95

program divide Makesureyouunderstandthis


thoroughly!
implicit none
integer :: x
real :: y
x = 1
y = x/3
print *, y
end program divide

Andrunit.Thisprogramproducesthefollowingoutput:

0.00000
Somethingoddishappening.Theproblemistheline:

y=x/3

FORTRANevaluatestherighthandsideoftheassignmentfirstusingintegerarithmetic,because
bothxand3areinteger.1dividedby3cannotbestoredasaninteger,andsothevalue0isreturned.
Theresult,0,isthenconvertedtoarealnumberandtheassignedtoy.

Replacethelineinprogramdivide

x = 1 by
x = 10
Youroutputshouldnowbe:

3.00000
Canyouseewhatishappening?FORTRANiskeepingtheintegerpartoftheanswerandthrowingthe
restaway.

CopyrightJanetANicholson2011 17 fortrantutorial.com
Togetoverthisproblem,wehavetosignaltoFORTRANthatwewantittocalculatetherighthand
sideoftheexpressionusingrealarithmetic.Ifwewanttokeepxasintegerdatatype,wecouldre
writeourexpressionasfollows:

y=x/3.0

Thepresenceofarealnumberontherighthandsidecausestherighthandsideoftheexpressionto
beevaluatedusingfloatingpointarithmetic.

Actually,theproblemisevenmorecomplicated!Wherewehaveanexpressionlike

y=x*((2**i)/3)

wherexandyarerealandiisinteger,FORTRANcomputestheresultinstages:

Firstitcalculates(2**i)/3andevaluatesitasanintegernumber,thenmultipliestheresultbyxand
evaluatesitasreal.

Exercise3.2
Copycheck.f95toyourcomputer.

program check
!Integer and real arithmetic
implicit none
real :: x,y
integer i
x=2.0
i=2
y=x*((2**i)/3)
print *,y
y=x*((2.0**i)/3)
print *,y
end program check

andexamineitsoutput.Makesureyouunderstandwhythisishappening.

3.3 Thedoloop
Unlessweareabletoreexecutecode,wemightaswelluseacalculatorNowwestarttotake
advantageofthepowerofthecomputer.

Exercise3.3
Copyprogramloop.f95

program loop
implicit none
integer :: i
do i=0,20
print *,i
end do

CopyrightJanetANicholson2011 18 fortrantutorial.com
end program loop

Runtheprogram.Itprintsoutthenumbersfrom0to20instepsof1.

Note:
iiscalledaloopcounter.Inthisexample,ithasastartvalueofzero.
Allthestatementswithinthedoandenddoareexecuted.Inthisexamplethereisjustthe
onestatement,ieprint.
Eachtimethestatementsareexecuted,theloopcounter,i,isincrementedby1.
Whenthevalueofiis20,theloopterminates,andtheprogramresumesaftertheenddo.

Changethedostatementinprogramloopasfollows:

do i = 50,70,2

Runtheprogram.Whathappens?

Thethirdargumentinthedostatement,istheincrementstep.Ifomitted,thevalueistakenas1.

Loopscanalsodecrement:trythis

do i = 5,-5,-2


Exercise3.4

Usingadolooptogenerateintegervaluesofxbetween10and10instepsof1,writeaprogram
thatconstructsatableofvaluesof

y=1.0/x

Whathappenedwhenxhadthevaluezero?Useanif,endiftotestfortheconditionthatgivesthe
incorrectvalue,andprintoutanappropriatemessage.Compareyourresultwithdivbyzero.f95.

Divisionbyzeroisoneofthecommonestreasonsforaprogramtofail.

3.4 NestedDoLoops
Wewanttoconstructatableofvaluesforzwhere

z=xy

forvaluesof xintherange1to2instepsof0.5and
yintherange1to2instepsof0.5

Workthroughthenextexercisewhichillustratesthis:

CopyrightJanetANicholson2011 19 fortrantutorial.com
Exercise3.5
Copyprogramxytab.f95toyourfilespace.

programxytab
implicit none
!constructs a table of z=x/y for values of x from 1 to 2 and
!yfrom1to4instepsof.5
real :: x, y, z
print*,'xyz'
do x = 1,2
do y = 1,4,0.5
z = x/y
print *, x,y,z
end do
end do
end program xytab

Examineitsoutput.Noticetheuseofthefirstprinttogiveaheadingtothetable.

3.5 Usingloopstodosummation
Earlieron,wediscussedtheideaofassignments.

x=1.0

meansstorethevalue1.0inthememorylocationcalledx.

Ifwehadthefollowingcode:

x=1.0
x=x+1.0
print*,x

Canyouguesswhatvaluewouldbeprintedoutforx?

Theanswerwouldbe2.0.

Bearinginmindthedefinitionofanassignment,thestatement Reallyimportant!

x=x+1.0

meansadd1.0tothevaluecurrentlystoredinmemorylocationxandthenstoretheresultin
memorylocationx.

CopyrightJanetANicholson2011 20 fortrantutorial.com

Exercise3.6
Copyfileincrement.f95toyourfilespaceandexamineitsoutput.
program increment
implicit none
integer :: i
real :: x
x=1.0
do i=1,10
x=x+1.0
print *, i,x
end do
end program increment

Notecarefullythatwehavesettheinitialvalueofxoutsideofthedoloop.Whyhavewe
donethis?Ifyouaren'tsurechangethecodetoputthelinex=1.0insidetheloopthen
examinetheoutput.
Itisimportanttounderstandthatifweuseconstructionssuchasx=x+1.0,thenitisvitalto
initialisextosomevalue.Ifwedon't,itispossiblethatthevaluemightbesettoanyrandom
number.Runtheprogram,makeanoteofthefinalvalueofxthenputanexclamationmark
infrontofthex=1.0statementandruntheprogramagain.

Exercise3.7
Editthelinex=x+1.0inprogramincrement.f95,andchangeittox=x*i.Reruntheprogramand
examinetheoutput.Whatissignificantmathematicallyaboutthesequenceofnumbersthathasbeen
generated?

CopyrightJanetANicholson2011 21 fortrantutorial.com
4 UsingFilesandExtendingPrecision
4.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Readfromandwritetofiles
Useextendedprecision

4.2 Readingfromfiles
Intherealworld,mostofthedataweuseforourprogramswillbekeptinfiles.Wejustneeda
modificationtothereadstatementthatwearealreadyfamiliarwithtodothis.
Thisprogramreads3numbersfromafilecalled'mydata.txt'intoanarray.UseWindowsNotepadto
createsuchafileforyourself,orcopythefilefrommydata.txtwhichisonthewebsite.
program readdata
implicit none
!reads data from a file called mydata.txt
real :: x,y,z
open(10,file='mydata.txt')
read(10,*) x,y,z
print *,x,y,z
end program readdata
Thenewmaterialherearethelines
open(10,file='mydata.txt')
read(10,*) x,y,z
Theopenstatementlinksthefilecalled'mydata.txt'withaninputdevicenumbered10(itdoesn't
havetobe10,itcouldbeanypositiveinteger).Toreadfromdevice10,wejustuseitasthefirst
argumentinthereadstatement.

Exercise4.1
UseNotepadtocreateafilecalledevenodd.txt.Inthefiletype10numbers,oneperline.Writea
programthatreadsdatafromevenodd.txtonelineatatime.Checkifeachnumberisevenoroddand
printoutasuitablemessage.Onewaytocheckifanumberisevenoroddistousethemodintrinsic
function,likethis

if (mod(num,2)>0) then

modreturnstheremainderofthefirstargumentdividedbythesecond.Ifthereturnvalueisgreater
thanzero,thenthenumbermustbeodd.Checkprogramevenodd.f95toseeifyouarecorrect.

CopyrightJanetANicholson2011 22 fortrantutorial.com

4.3 Writingtofiles
Thisisasimilarideatoreadingfromfiles.Weneedanewstatement,though,insteadofprint,weuse
write.
program io2
!illustrates writing arrays to files
implicit none
real :: num
integer :: i
open(12,file='myoutput')
do i = 1,100
num = i/3.0
write(12,*) nums
end do
print *, 'finished'
end program io2

Exercise4.2
Writeaprogramwhichreadsinnumbersfromafileoneatatime.Ifthenumberispositive,itshould
storeitinafilecalled'positive.txt'andnegativenumbersinafilecalled'negative.txt'.

4.4 Extendingtheprecision
Sofar,wehaveusedtwotypesofvariables,realandinteger.Theproblemsofar,asyouwillhave
noticedonoutput,isthatweareextremelylimitedbythenumberofsignificantdigitsthatare
availableforcomputation.Clearly,whenwearedealingwithiterativeprocesses,thiswillleadrapidly
toerrors.Wecan,however,extendtheprecisionavailablefromthesingleprecisiondefault,which
givesus6figuredecimalprecisionto15figuresbyusinganewspecificationforrealnumbers.
program extended
implicit none
integer, parameter :: ikind=selected_real_kind(p=15)
real (kind=ikind) :: sum,x
integer :: i
sum=0.0
do i=1,100
x=i
sum = sum + 1.0/(x**6)
end do
print *, sum
end program extended

producesthefollowingoutput:
1.01734306196
Don'tbeputoffbytheoddlookingcode.Inpractice,thewayofsettingupthisextendedprecision,is
prettymuchthesameforeveryprogram.
Westatetheprecisionwewantbytheargumentp
integer, parameter :: ikind=selected_real_kind(p=15)

CopyrightJanetANicholson2011 23 fortrantutorial.com
inthiscase,15decimalplaces.ikindisanewdatatypeaparameter.FORTRANreturnsavalueto
theparameterikindthatwillbeadequatetoprovide15digitprecision.Thiscodewillworkonany
machineirrespectiveofthearchitecture.
Wedeclarethatthevariablesareusingextendedprecisionby
real (kind=ikind) :: sum,x
Validvaluesforpare6,15and18.Thedefaultvalueforpis6.Ifyouaskformoreprecisionthan18
digits,thecompilerwillcomplainwithanerrormessage.Trychangingthevaluesofpandseewhat
effectthishasontheoutput.

ThetroublewithPRINTisthattheprogrammerhasnocontroloverthenumberofdigitsoutput
irrespectiveoftheselectedprecision.

Lateronwe'llcomebacktothiswhenwelearnabouttheWRITEstatement,andoutput
formatting.

NoteUnlikevariables,parametersmaynotchangeoncetheyaredeclared.
Ifwewanttouseconstantsinaprogramthatusesextendedprecision,wehavetotellFORTRANthat
theyarealsoextendedprecisionexplicitly.Thisleadstotheratherstrangesyntaxyoucanseeinthe
followingprogram.

program extendedconstants
!demonstrates use of extended precision
implicit none
integer, parameter :: ikind=selected_real_kind(p=18)
real (kind=ikind) :: val,x,y
val=10/3
print*,val !10/3 calculated as integer - wrong!
x=10.0
y=3.0
val=x/y !x/y assigned to extended precision - right!
print*,val
val=10.0_ikind/3 !extend precision constant - right!
print*,val
val=10.0/3.0 !real constants - wrong!
print*,val
val = .12345678901234567890 !real constants - wrong!
print *, val
val = .12345678901234567890_ikind !ext precision consts - right!
print *, val
end program extendedconstants

Youshouldrunthisprogramforyourselfandthinkcarefullyaboutitsimplications.Thisprogram
demonstrateshoweasyitistogetcalculationswrong.Illleavethistoyoutoexperimenttoensure
thatyoufullyunderstandtheimportanceofproperlydeclaringvariablesandtheuseofconstantsin
FORTRANprogramming.Asystematicapproachtoyourprogrammingwillreducetheriskoferrorsas
willrunningprogramswithtestdatathathaveknownsolutionssothatyoucanconfirmthatyour
programiserrorfree.

CopyrightJanetANicholson2011 24 fortrantutorial.com
4.5 Magnitudelimitations
Wehavealreadyobservedthatthereisalimitationoftheaccuracywithwhichwecandocalculations
inFORTRAN(andindeed,any,computerlanguage).Therearealsolimitationsonthemagnitudeofa
number.Thevariousmagnitudeandprecisionlimitsaresummarizedinthefollowingtable:

Valueofp Decimalplaces Range


6 6(default) 1038
15 15 10307
18 18 104931

Exercise5.3
Toillustratetheselimitscopyfilemagnitude.f95andruntheprogram.Takeawhiletogetafeelfor
whatisgoingon.Tryinputtingvariousvaluesforthevariablemaxpower(eg400).Canyouconfirm
thatthetableaboveiscorrect?

Oneinterestingconstructis

print*,i,2.0_ikind**i

Here,wearetellingthecompilerthattherealconstant2.0isalsousingextendedprecision.Check
whathappensifyouselectextendedprecision(option3)andenteravalueofmaxpowerof400.See
whathappensifyourewritethelinetobe

print*,i,2.0**i

Runtheprogramagainandenterthesamevalues.Canyouexplainwhatisgoingon?

4.6 Convergenceexitingloopsonacondition
Intheprogramextended.f95,wefoundthesumof
x 10
1
x 1
6

x
Itisusefultodetermineatwhatpointsuchsumsconvergetoasteadyvalueotherwisewemay
makearbitraryassumptionsaboutthesummationrange.Clearly,apointwillbereached,withinthe
precisionrangethatcanbehandledonourcomputer,thattheterm
1
6

x
willbetoosmalltocontributetothesum.Atthispointweshouldexittheloopotherwisethe
programwilldomorecomputationthanisrequired.

Onewaytodothisistocomparethevalueofthevariablesumwithitspreviousvalue,andifthe
differencebetweenthetwoisverysmall,thenexittheloop.

CopyrightJanetANicholson2011 25 fortrantutorial.com
programwhileloop
implicit none
integer, parameter :: ikind=selected_real_kind(p=15)
real (kind=ikind) :: sum,previoussum,x,smallnumber,error
integer :: i
sum=0.0
previoussum=0.0
smallnumber = 10.0**(-15.0)
do i=1,1000
x=i
sum = sum + 1.0 /(x**6)
error=abs(sum-previoussum)
if (error<smallnumber) then
print *,'sum ',sum,' number of loops ',i
exit
end if
previoussum = sum
end do
end program whileloop

IMPORTANTNOTE
Intherealworld,wehavetomakechoicesabouttheamountofprecisionweneedtoworkto.Itis
pointlessaskingfor15digitsofprecisionif,forexample,wecanonlytakeameasurementto+or
1%accuracy!

Itisnotnecessarytoalwaysusealoopcounterinadoloop.Ifwedon'tactuallyspecifyacounter,
theprogramwillloopforever.ConstructslikethisareOK:

smallnumber = .0000001_ikind
do
print *, 'enter a positive number '
read *, number
if (number <= smallnumber) exit
end do
Thedisadvantageisthat,ifyougetthecodewrong,youruntheriskoftheprogramloopingforever
generallyit'ssafertousealoopcounter!

CopyrightJanetANicholson2011 26 fortrantutorial.com

5 ArraysandFormattedI/O
5.1 Aims
Bytheendofthisworksheetyouwillbeableto:
Understandtheuseofarrays
Improvetheappearanceofyouroutput

5.2 Arrays
Letusimaginethatwewanttofindtheaverageof10numbers.One(crude)methodisshowninthe
nextprogram.
program av
real :: x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,average
read *, x1,x2,x3,x4,x5,x6,x7,x8,x9,x10
average= (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10)/10
print *, 'the average is ',average
print *, 'the numbers are:'
print *, x1
print *, x2
print *, x3
print *, x4
print *, x5
print *, x6
print *, x7
print *, x8
print *, x9
print *, x10
end program av
Thisapproachismessy,involvesalotoftypingandispronetoerror.Imagineifwehadtodealwith
thousandsofnumbers!
Thewayaroundthisistousearrays.Anarrayisalistthatwecanaccessthroughasubscript.To
indicatetoFORTRANthatweareusinganarray,wejustspecifyitssizewhenwedeclareit.
real, dimension(100) ::x
.
.
x(1) = 3
x(66) = 4
Thissnippetofcodeallocates100memorylocationstothearrayx.Toaccessanindividuallocation,
calledanarrayelement,weuseasubscripthereweareassigningthenumber4tothe66thelement
ofarrayxand3tothe1stelement.

Nowlet'sreturntoprogramavatthestartofthisworksheet,we'llrewriteitusinganarray.

CopyrightJanetANicholson2011 27 fortrantutorial.com

program av2
implicit none
real ,dimension(10) :: x
real :: average,sum
integer :: i
print *, 'enter 10 numbers'
sum=0.0
do i=1,10
read *, x(i)
sum=sum+x(i)
end do
average=sum/10
print *, 'the average is ',average
print *, 'the numbers are'
print *,x
end program av2

Noticethatifwetype

print*, x
theprogramwillprintouttheentirecontentsofthearray.

Theadditionalbenefitofthisprogramisthatwithveryfewchanges,wecouldmakeitdealwithany
numberofitemsinourlist.Wecanimproveonthisstillfurtherbymakingusetheparameterdata
type:

program av3
!just change the value of the parameter to change the size of the
!array
implicit none
integer, parameter :: imax = 10
real,dimension(imax) :: x
real :: average,sum
integer :: i
print *, 'enter ,imax, numbers'
sum=0.0
do i=1,imax
read *, x(i)
sum=sum+x(i)
end do
average=sum/imax
print *, 'the average is ',average
print *, 'the numbers are'
print *,x
end program av3
Notethisisanexampleofgoodprogramming.Thecodeiseasilymaintainableallwehavetodoto
findanaverageofalistofnumbersofanysizeisjusttochangethesizeoftheparameterimax.We
canalsoallocatethesizeofthearrayatruntimebydynamicallyallocatingmemory.

CopyrightJanetANicholson2011 28 fortrantutorial.com
Thefollowingprogramdemonstratestheuseofarrayswherewedonotknowthesizeofthearray.

program alloc
implicit none
integer, allocatable,dimension(:):: vector
!note syntax - dimension(:)
integer :: elements,i
print *,'enter the number of elements in the vector'

read *,elements
allocate(vector(elements))
!allocates the correct amount of memory
print *,' your vector is of size ',elements,'. Now enter each
element'
do i=1,elements
read *,vector(i)
end do
print *,'This is your vector'

do i=1,elements
print *,vector(i)
end do

deallocate(vector)
!tidies up the memory

end program alloc

Theprogramiscalledalloc.f95andcanbecopiedfromthewebpage.Noteinparticularthebolded
lines.Thenewwayofdeclaringthearrayvectortellsthecompilerthatitisallocatableiethesize
willbedeterminedatruntime.

WeshalllookatthisfurtherinSection7.


Exercise5.1
Writeaprogramthataskstheuserhowmanynumberstheywanttoenter,callthisvalueimax.
Allocateimaxelementstotwoarrays,aandb.Readinimaxnumberstoaanddothesametob.Print
outthearraysa,bandprintoutthesumofaandb.Compareyourattemptwithsumalloc.f95.

5.3 Arraymagic

Oneofthebenefitsofarraysisthatyoucaneasilydooperationsoneveryelementbyusingsimple
arithmeticoperators.

program ramagic
implicit none
real ,dimension(100) :: a,b,c,d
open(10,file='data.txt')
read(10,*) a
b=a*10
c=b-a

CopyrightJanetANicholson2011 29 fortrantutorial.com
d=1
print *, 'a= ',a
print *, 'b= ',b
print *, 'c= ',c
print *, 'd= ',d
end program ramagic

Exercise5.2
Copyprogramramagic.f95andfiledata.txttoyourownfilespace.Runtheprogramandexaminethe
output.

Exercise5.3
Writeaprogramthatfillsa10elementarrayxwithvaluesbetween0and.9instepsof.1.Printthe
valuesofsin(x)andcos(x)usingthepropertiesofarraystosimplifyyourprogram.Compareyour
answerwithramagic2.f95.

5.4 Multidimensionalarrays
Thearrayswehavelookedatsofarhavebeenonedimensional,thatisasinglelistofnumbersthat
areaccessedusingasinglesubscript.Inconcept,1dimensionalarraysworkinasimilarwayto
vectors.Wecanalsousetwodimensionalarrayswhichconceptuallyareequivalenttomatrices.

So,forexample,

Integer,dimension(5,5)::a

setsupastoragespacewith25integerlocations.

Thenextprogramcreatesa2dimensionalarraywith2rowsand3columns.Itfillsalllocationsin
column1with1,columns2with2,column3with3andsoon.

program twodra
implicit none
integer,dimension(2,3) :: a
integer ::row,col,count
count = 0
!creates an array with 3 cols and 2 rows
!sets col 1 to 1, col2 to 2 and so on
do row=1,2
count=0
do col =1,3
count=count+1
a(row,col)=count
end do
end do
do row=1,2
do col =1,3
print *,a(row,col)
end do
end do
end program twodra

CopyrightJanetANicholson2011 30 fortrantutorial.com
FORTRANactuallyallowstheuseofarraysofupto7dimensions,afeaturewhichisrarelyneeded.To
specifyaextendedprecision3dimensionalarraybwithsubscriptsrangingfrom1to10,1to20and1
to30wewouldwrite:
real (kind=ikind),dimension(10,20,30) :: b

Exercise5.4
Usinga4*4arraycreateanidentitymatrix,thatis,amatrixoftheform:

1000
0100
0010
0001

andoutputit.Wouldn'titbeniceifwecouldactuallyoutputthematrixelementsinrowsand
columns?Attheendofthissectionweshallseeexactlyhowtodothis.

5.5 Formattingyouroutput
Youmaynowbewonderingifthereisanywaytohavebettercontroloverwhatyouroutputlooks
like.Sofarwehavebeenusingthedefaultoutputoptionthat'swhatthe*'sareforinthewriteand
printstatements:

write(10,*) x,y,z
print *, 'program finished'

Exercise5.5
Copyformat.f95,andrunit
program format
implicit none
!demonstrates use of the format statement
integer, parameter :: ikind=selected_real_kind(p=15)
real , dimension(4) :: x
integer, dimension(4) :: nums
integer :: i
real(kind=ikind),dimension(4) :: computed
!fill up the arrays with something
do i = 1,4
nums(i) = i * 10
computed(i) = cos(0.1*i)
x(i) = computed(i)
end do
print *,'nums - integer'
write(*,1) nums
1 format(2i10)
print *, 'x - real'
write(*,2) x
2 format(f6.2)
print *, 'computed - double precision'
write(*,3) computed
3 format(f20.7)

CopyrightJanetANicholson2011 31 fortrantutorial.com
end program format
Youcanseethatthewriteandformatstatementscomeinpairs.

write(outputdevice,label)variable(s)
label format(specification)

Weareusinginthisexamplea*astheoutputdeviceinotherwords,thescreen.

Theformatstatementcanactuallygoanywhereintheprogram,butbyconventionweusuallyplace
themjustaftertheassociatedwriteoralltogetherattheendoftheprogram.It'sjustamatterof
taste.

Thetrickyparthereisthespecification.Therearedifferentspecificationsforinteger,real,and
charactervariables.

5.5.1 Integer Specification


Generalform:nim

Rightjustified
misthenumberofcharacterspacesreservedforprinting(includingthesignifthereisone)
Iftheactualwidthislessthanm,blanksareprinted
nisthenumberofintegerstooutputperline.Ifomitted,onenumberisoutputperline.

5.5.2 Floating point Specification


Generalform:nfm.d
Rightjustified
misthenumberofcharacterspacesreservedforprinting(includingthesignifthereisone),
andthedecimalpoint.
Iftheactualwidthislessthanm,blanksareprinted
nisthenumberofrealnumberstooutputperline.Ifomitted,onenumberisoutputper
line.
disthenumberofspacesreservedforthefractionalpartofthenumberfilledwith0'sif
fewerspacesareneeded.Ifthefractionalpartistoowideitisrounded.

Ifthetotalwidthforoutput(m)istoosmall,FORTRANwilljustoutput*'s.

Rule m>= widthoftheintegerpartplus


dplus
1(spacefordecimalpoint)plus
1(spaceforsignifnegative)

Essentially,makemniceandwideandyouwon'thaveanytrouble!

5.5.3 Exponential Specification


GeneralformnEm.d
Alternativespecificationforoutputtingreal
disthenumberofdecimalplaces
misthetotalwidthofthefieldincludingthesign(ifany),thecharacterEanditssign,the
decimalpointandthenumberofplacesofdecimals.Againmakemniceandwidetoensure
thefieldisproperlyprintedout.
nisthenumberofexponentialnumberstooutputperline.Ifomitted,onenumberisoutput
perline.

CopyrightJanetANicholson2011 32 fortrantutorial.com
Example
real :: a,b
a = sqrt(5.0)
b = -sqrt(a)
write(*,10) a,b
10 format(2E14.5)
produces:
0.22361E+01 -0.14953E+01

5.5.4 Character Specification


GeneralformnAm
nisthenumberofstringstoprint
misthemaximumnumberofcharacterstooutput

Example:
program chars
implicit none
character ::a*10,b*10
a='hello'
b='goodbye'
write(*,10) a,b
10 format(2a10)
end program chars

Exercise5.6

Usingtheformatspecificationsinformat.f95asaguide,produceatableof
xex
where0 x 1 ,forvaluesofxinincrementsof0.1.Writeyouroutputtoafilecalledmyoutput.
Ensurethatyouroutputlinesupneatlyincolumns.Anexampleprogramisneatoutput.f95isavailable
onthewebsite.

5.6 ImpliedDoLooptowritearrays
Sofar,themethodwehaveusedforinputandoutputofarraysis:
integer :: col,row
real :: ra(10,10)
!using do loop
do row = 1,10
do col = 1,10
read *, ra(row,col)
write(*,*) ra(row,col)
end do
end do

CopyrightJanetANicholson2011 33 fortrantutorial.com
Thetroublewiththismethodisthattherowsandcolumnsarenotpreservedonoutput.An
alternative,andneatermethodistouseanimplieddoloopinthewritestatement.
real :: ra(10,10)
integer :: row,col
!use implied do
do row = 1,10
do col = 1,10
read *, ra(row,col)
end do
end do
do row=1,10
write(*,10) (ra(row,col),col=1,10)
end do
10 format(10f5.1)

Exercise5.7
InExercise5.4youwroteaprogramtoproduceandidentitymatrix.Applywhatyouknowabout
formattingnowtomakeaneatlyformattedmatrixonscreen.Thereisanexampleidentity1.f95
availableonthewebsite.

CopyrightJanetANicholson2011 34 fortrantutorial.com
6 SubroutinesandFunctions

6.1 Aims
Bytheendofthisworksheetyouwillbeableto:

Understandtheuseofsubroutinesandfunctionstomakeyourcodemoreefficientand
easiertoread.

6.2 Reusingcodethesubroutine

Examinethefollowingprogram

program output
implicit none
real,dimension(3) :: a,b,c
character :: answer*1
!initialise arrays
a = 1.5
b = 2.5
c = 3.5
write(*,1) 'a',a
print *, 'type y to continue or any other key to finish'
read *, answer
if (answer /= 'y') stop
write(*,1) 'b',b
print *, 'type y to continue or any other key to finish'
read *, answer
if (answer /= 'y') stop
write(*,1) 'c',c
print *, 'type y to continue or any other key to finish'
read *, answer
if (answer /= 'y') stop
write(*,1) 'a*b*c',a * b * c
1 format(a,3f8.3)
end program output

Theprogramsetsupsomearraysandthenoutputsthem.Atthreestagesintheprogram(bolded),it
askswhetheritshouldcontinue;itstopsiftheanswerisnot'y'.Noticethatthethreeboldedpartsof
thecodeareidentical.

Simpleenoughbutlookattheamountofcode!Mostofitisthesamewouldn'titbenicetoreuse
thecodeandcutdownonthetyping?Theansweristousesubroutines.

CopyrightJanetANicholson2011 35 fortrantutorial.com
program output1
implicit none
real,dimension(3) :: a,b,c
!initialise arrays
a = 1.5
b = 2.5
c = 3.5
write(*,1) 'a',a
call prompt()
write(*,1) 'b',b
call prompt()
write(*,1) 'c',c
call prompt()
write(*,1) 'a*b*c',a * b * c
1 format(a,3f8.3)
end program output1
!++++++++++++++++++++++++++++++++++++++++++++++
subroutine prompt()
!prompts for a keypress
implicit none
character answer*1
print *, 'type y to continue or any other key to finish'
read *, answer
if (answer /= 'y') stop
end subroutine prompt
Examinethecode,eachtimeweusetype

callprompt()

theprogramjumpstotheline

subroutineprompt()

thenexecuteseachlineofthecodeitfindsinthesubroutineuntilitreachestheline

endsubroutineprompt

andthenreturnstothemainprogramandcarriesonwhereitleftoff.
Theprogramismucheasiertounderstandnow.Allthecodeforpromptingisinoneplace.Ifweever
needtochangethecodewhichpromptstheusertocontinue,wewillonlyeverneedtochangeit
once.Thismakestheprogrammoremaintainable.

6.3 Argumentstosubroutines

Wehaveseenthatsubroutinesareveryusefulwhereweneedtoexecutethesamebitofcode
repeatedly.

Thesubroutinecanbethoughtofasaseparateprogramwhichwecancallonwheneverwewishto
doaspecifictask.Itisindependentofthemainprogramitknowsnothingaboutthevariablesused
inthemainprogram.Also,themainprogramknowsnothingaboutthevariablesusedinthe
subroutine.Thiscanbeusefulwecanwriteasubroutineusinganyvariablenameswewishandwe
knowthattheywillnotinterferewithanythingwehavealreadysetupinthemainprogram.

CopyrightJanetANicholson2011 36 fortrantutorial.com

Thisimmediatelyposesaproblemwhatifwewantthesubroutinetodocalculationsforusthatwe
canuseinthemainprogram?Thefollowingprogramusesargumentstodojustthat.

Example:aprogramthatcalculatesthedifferenceinvolumebetween2spheres.

program vols
!Calculates difference in volume of 2 spheres
implicit none
real :: rad1,rad2,vol1,vol2
character :: response
do
print *, 'Please enter the two radii'
read *, rad1,rad2
call volume(rad1,vol1)
call volume(rad2,vol2)
write(*,10) 'The difference in volumes is, ',abs(vol1-vol2)
10 format(a,2f10.3)
print *, 'Any more? - hit Y for yes, otherwise hit any key'
read *, response
if (response /= 'Y' .and. response /= 'y') stop
end do
end program vols
!________________________________________________
subroutine volume(rad,vol)
implicit none
real :: rad,vol,pi
!calculates the volume of a sphere
pi=4.0*atan(1.0)
vol=4./3.*pi*rad*rad*rad
!It's a little quicker in processing to do r*r*r than r**3!
end subroutine volume
Whentheprogramreachesthelines
call volume(rad1,vol1)
Itjumpstotheline
subroutine volume(rad,vol)

Thevalues,rad1andvol1arepassedtothesubroutine.Thesubroutinecalculatesavalueforthe
volumeandwhentheline:
end subroutine volume
isreached,thevalueofthevolumeisreturnedtothemainprogram

Pointstonoticetheseareveryimportantpleasereadcarefully
Youmayhaveseveralsubroutinesinyourprogram.Ideally,asubroutineshoulddoaspecific
taskreflectedbyitsname.
Allthevariablesinsubroutines,apartfromtheonespassedasarguments,are'hidden'from
themainprogram.Thatmeansthatyoucanusethesamenamesinyoursubroutineasinthe
mainprogramandthevaluesstoredineachwillbeunaffectedunlessthevariableispassed
asanargumenttothesubroutine.
Itisveryeasytoforgettodeclarevariablesinsubroutines.Alwaysuseimplicitnoneinyour
subroutinestoguardagainstthis.

CopyrightJanetANicholson2011 37 fortrantutorial.com
Allthevariablesinthesubroutinemustbedeclared.
Thepositioningofthearguments(inthiscase,radandvol)isimportant.Thesubroutinehas
noknowledgeofwhatthevariablesarecalledinthemainprogram.Itisvitalthatthe
argumentsagreebothinpositionandtype.So,ifanargumenttothesubroutineisrealin
themainprogram,itmustalsoberealinthesubroutine.
Ifanargumenttothesubroutineisanarray,itmustalsobedeclaredasanarrayinthe
subroutine.
Exercise6.1
Writeaprogramthatcalculatesthedifferenceinareabetweentwotriangles.Yourprogramshould
prompttheuserfortheinformationitneedstodothecalculation.Useasubroutinetocalculatethe
actualarea.Passinformationtothesubroutineusingarguments.

6.4 UserDefinedFunctions
WehavealreadymetFORTRANintrinsicfunctionslikeabs,cos,sqrt.Wecanalsodefineourown
functionstheyworkinasimilarwaytosubroutines.

Asanexample,let'swriteaprogram(func.f95)thatdoessometrigonometry.Asyouknow,thetrig
routinesinFORTRANuseradians,notdegreessoitwouldbenicetowriteafunctionthatdoesall
theconversionforus.
print *,'Enter a number'
read *, a
pi=4.0*atan(1.0)
print *,'the sine of ',a,' is ',sin(a*pi/180)
Inthissnippet,wearehavingtocodetheconversionfromdegreestoradiansdirectlyintothemain
partoftheprogram.That'sOKfora'oneoff',butwhatifweneededtodotheconversionseveral
times.Nowlookatthis:
program func
!demonstrates use of user defined functions
implicit none
integer, parameter :: ikind=selected_real_kind(p=15)
real (kind=ikind):: deg,rads
print *, 'Enter an angle in degrees'
read *, deg
write(*,10) 'sin = ',sin(rads(deg))
write(*,10) 'tan = ',tan(rads(deg))
write(*,10) 'cos = ',cos(rads(deg))
10 format(a,f10.8)
end program func
!_____________________________________________
function rads(degrees)
implicit none
integer, parameter :: ikind=selected_real_kind(p=15)
! returns radians
real (kind=ikind) :: pi,degrees,rads
pi=4.0_ikind*atan(1.0_ikind)
rads=(degrees*pi/180.0_ikind)
end function rads
Whatwehavedone,ineffect,istocreateourownfunctionrads,whichisusedinanidenticalwayto
theintrinsiconesyouhaveusedalreadylikesqrt,cos,andabs.

Whentheline

CopyrightJanetANicholson2011 38 fortrantutorial.com

write(*,10) 'sin = ',sin(rads(deg))
isreached,theprogramjumpsto

function rads(degrees)
thevalue,degrees,ispassedtothefunction.Thefunctiondoessomecomputation,thenfinally
returnsthecalculatedvaluetothemainprogramwiththeline

rads=(degrees*pi/180.0_ikind)

Notecarefullythatitdoesn'treturnthevalueintheargumentlist(asdoesasubroutine)butactually
assignsthevaluetoitsownnamerads.

Thefunctionradsconvertsthevalueoftheargument,degrees,toradians.
Noticethatwemustdeclarethedatatypeofthefunctionbothinthemainprogram,andin
thefunctionitselfasifitwereavariable.
Functionsreturnonevalue.Thisvalue,whencalculated,isassignedtothenameofthe
functionasifitwereavariable
rads=(degrees*pi/180.0_ikind)


Exercise6.2
Writeaprogramthatincludesafunctioncalled

realfunctionaverage(n,list)

wherenisintegerandisthenumberofitemsinthelist,andlistisarealarray.

Writesuitablecodeforreadingthenumbersfromafile(orkeyboard),andoutputtheaverageofthe
numbers.

Exercise6.3
Writeaprogramthatallowsausertoenterthesizeofasquarematrix.Intheprogramwritea
subroutinetocomputeafinitedifferencematrix.Ensureyouroutputisneatlyformattedinrowsand
columns.

So,fora10by10matrix,weexpectoutputtolooklikethis

2100000000
1210000000
0121000000
0012100000
0001210000
0000121000
0000012100
0000001210
0000000121
0000000012

Checkyourattemptwithfinite.diffs.f95onthewebsite.

CopyrightJanetANicholson2011 39 fortrantutorial.com
7 AdvancedTopics

7.1 Aims
Bytheendofthisworksheetyouwillbeableto:

Usearrayfunctions
Createlargerprogramsaidedby"FlowCharts"

7.2 ArrayFunctions
FORTRANprovidesanumberofintrinsicfunctionsthatareusefulforworkingwitharrays.Among
thesearesomewhicharespecificallyaimedatworkingwithmatricesandvectors.

MATMUL Matrix/vector Matrixmultiplicationoftwomatricesoramatrix


andavector.
DOT_PRODUCT Vector Scalar(dot)productoftwovectors
TRANSPOSE Matrix Transposeofamatrix
MAXVAL Anyarray Maximumvalueofanarray,orofalltheelements
alongaspecifieddimensionofanarray.
MINVAL Anyarray Minimumvalueofanarray,orofalltheelements
alongaspecifieddimensionofanarray.
SUM Anyarray Sumofalltheelementsofanarray,orofallthe
elementsalongaspecifieddimensionofanarray.

Programmatrixmul.f95,demonstratestheuseofthesefunctions.Additionally,itincludestwo
subroutinesthatarelikelytobeusefulwhenhandlingmatrix/arraymanipulations:fill_arraywhich
fillsthearrayelementsandoutputrawhichprintsthevaluesofthearrayelementstothescreen.This
programisalsoanexampleofdynamicmemoryallocation.

program matrixmul
!demonstrates use of matmul array function and dynamic
!allocation of array
real, allocatable, dimension(:,:) :: ra1,ra2,ra3
integer :: size
!initialize the arrays
print*, 'Shows array manipulation using SQUARE arrays.'
print*, 'Allocate the space for the array at run time.'
print*, 'Enter the size of your array'
read *, size
allocate(ra1(size,size),ra2(size,size),ra3(size,size))
print*, 'enter matrix elements for ra1 row by row'
call fill_array(size,ra1)
print*, 'enter matrix elements for ra2 row by row'
call fill_array(size,ra2)
!echo the arrays
print *,'ra1'
call outputra(size,ra1)

CopyrightJanetANicholson2011 40 fortrantutorial.com
print *,'ra2'
call outputra(size,ra2)
!demonstrate the use of matmul and transpose intrinsic
!functions
ra3=matmul(ra1,ra2)
print *,'matmul of ra1 and ra2'
call outputra(size,ra3)
ra3=transpose(ra1)
print *,'transpose of ra1'
call outputra(size,ra3)
deallocate(ra1,ra2,ra3)
end program matrixmul
!---------------------------------------------------------
subroutine outputra(size,ra)
implicit none
!will output a real square array nicely
integer :: size,row,col
real,dimension(size,size) :: ra
character :: reply*1
do row =1,size
write(*,10) (ra(row,col),col=1,size)
10 format(100f10.2)
!as we don't know how many numbers are to be output, specify
!more than we need - the rest are ignored
end do

print*,'__________________________________________________'
print*,'Hit a key and press enter to continue'
read *,reply
end subroutine outputra
!---------------------------------------------------------
subroutine fill_array(size,ra)
implicit none
!fills the array by prompting from keyboard
integer :: row,col,size
real :: num
real, dimension(size,size) :: ra
do row=1,size
do col=1,size
print *, row,col
read *,num
ra(row,col)=num
end do
end do
end subroutine fill_array

CopyrightJanetANicholson2011 41 fortrantutorial.com

Exercise7.1

Writeaprogramtoreadin2squarematrices(ofanysize).Confirmthatthematricesobeytherule

(AB)T=BTAT

whereATisthetransposeofmatrixA.

Exercise7.2
Writeaprogramthatwillreada3X3matrixfromadatafile.Intheprogram,includeasubroutine
thatwillgenerateanycofactorcofofthematrixmat.Callthesubroutinecofactorandusethese
arguments:

subroutine cofactor(i,j,mat,cof)
implicit none
real :: mat(3,3),minor(2,2),cof
integer :: elrow,elcol
! cof the cofactor of matrix mat for element i,j
.
.

Exercise7.3
UsetheprogramyoudevelopedExercise7.2tocalculatethedeterminantofa3X3matrix.

7.3 WritingREALprogramsFlowCharts

NowthatyouknowallthemainelementsofFORTRAN95,youareinapositiontoapplyyourskillsto
writingREALprograms.Unlikemostoftheexercisesintheseworksheets,REALprogramstendtobe
ratherlarge.Inlargeprograms,theunderlyinglogiccanoftenbedifficulttofollow.

Ithelps,therefore,bothinthedevisingofaprogramandlaterinitsmaintenance,tohaveaplanof
whatyouintendtheprogramtodo.Letstake,asanexample,aprogramthatworkslikeacalculator.

Theflowchartisshownonthenextpage.Thelogicoftheprogram,asawhole,isclear.Detailslike
whatwillhappeninthesubroutinesisglossedoveratthisstage.

Incommercialprogramming,flowchartsareusuallyformalized,withspecificshapesforboxesthatdo
differentthings.Thatneednotconcernushere.Essentially,weuseflowchartstoprovideamapof
theunderlyinglogicflowintheprogramwhatconnectswithwhat.

CopyrightJanetANicholson2011 42 fortrantutorial.com

Start

Displaymenuofchoices

A,B,C,D

Userchooses A SubroutineSubtract

Subroutinemultiply


Subroutinepower
C

Subroutinetrig

Sorry,badinput

Haveyoufinished?

No
Yes


Stop

CopyrightJanetANicholson2011 43 fortrantutorial.com
DebuggingTips

7.4 Symptomsandprobablecauses
Haveyougotroundingerrors?
Dontdofloatingpointcalculationsusingintegers.Makesureyourprecisionisconsistentand
adequate.Makesuretheprecisionoftherighthandsideofanequationmatchesthetypeof
variableyouareassigningto.

Areyourcalculationscompletelywrong?
Initialiseallyourvariablesdontforgetarrays!
Makesureyourarraysarebigenoughtoholdallthedata.
Checkthatargumentspassedtosubroutinesagreeexactlyinsize,typeandposition
Istheprogramslogicworkingthewayitshould?

7.5 Wiseprecautionsandtimesavingtips
Youmustnottestfloatingpointnumbersforequality.Example:
if (x == 1) then...

doesnotwork.
Shouldyoubeusingtheabsolutevalueofacalculation?Example:
if (abs(x-y)<.00001) then
Donthaveoverlyelaboratelogicaltests.Itsprobablybettertotestoneortwothingsata
timeratherthanthissortofthing
if (((x.AND.y).OR.z > 10).OR.(.NOT. xx < 0)) then

youmightthinkyouunderstooditwhenyouwroteit,butimaginetryingtofigureoutwhats
happeningiftheprogrambreaks!

Don'ttryandwriteacomplicatedprogramallatonce.Writeitapieceatatimeandcheck
thateachpieceisworkingcorrectlybeforedoingthenextbit.
Useimplicitnoneatthestartofallprogramsandsubroutines.
Ifyourprogramneedsdatatobeenteredbytheuser,youwillsavehoursoftimebytaking
thetroubletoreadinthedatafromafilewhiletheprogramisindevelopment.
Alwaysdoatestfordivisionbyzerowhendividing.
BENEAT!Goodprogrammingislikeplainspeakingtheresnomileageintricky,difficultto
readcode.

7.6 Howtofindthebugs
Useaprintstatementtoprintoutthevalueswithintheprogramtakealookatthiscode
x = x + 1
z = x * y
print *, debug statement 1 value of x,y,z, x,y,z
do ii =1,10
z = x * ii
if (ii == 5) then
print *, debug do loop value of z when ii = 5,z
end if
end do
if (z>2000) then
print *, debug statement z>2000 value of z ,z
stop
end if
Noticehowwecanprintoutvaluesofspecificvariables,stoppingtheprogramifnecessary.

CopyrightJanetANicholson2011 44 fortrantutorial.com
Index

Arithmetic.....................................................11 exitingloops..................................................25
arithmeticoperators....................................11 ExponentialSpecification..............................32
Arrays...........................................................27 exponentiations............................................11
Assignment...................................................11 finitedifference............................................39
character........................................................8 floatingpointnumbers...................................8
CharacterSpecification.................................33 FloatingpointSpecification..........................32
Convergence.................................................25 FlowCharts.............................................40,42
DebuggingTips.............................................44 Formattingyouroutput................................31
DebuggingTips............................................44 function.........................................................39
dotproduct...................................................40 identity..........................................................31
dynamicmemoryallocation.........................40 ikind..............................................................26
dynamicallyallocatingmemory....................28 ImpliedDoLooptowritearrays...................33
errors..............................................................8 integer.............................................................8
Exercise1.1.....................................................4 IntegerSpecification.....................................32
Exercise1.2.....................................................6 intrinsicfunctions.............................11,12,40
Exercise1.3.....................................................7 logicaloperators...........................................14
Exercise1.4.....................................................9 loop...............................................................18
Exercise2.1...................................................11 loopcounter..................................................19
Exercise2.2...................................................12 Magnitude.....................................................25
Exercise2.3...................................................14 maintainable.................................................36
Exercise2.4...................................................15 matrix............................................................39
Exercise3.1...................................................17 Matrixmultiplication....................................40
Exercise3.2...................................................18 Mixingvariabletypes....................................17
Exercise3.3...................................................18 Multidimensionalarrays..............................30
Exercise3.4...................................................19 NestedDoLoops...........................................19
Exercise3.5...................................................20 operators........................................................6
Exercise3.6...................................................21 parameter.....................................................24
Exercise3.7...................................................21 Plato................................................................3
Exercise4.1...................................................22 precedence...................................................11
Exercise4.2...................................................23 precision....................................................8,23
Exercise5.1...................................................29 programmingstyle........................................11
Exercise5.2...................................................30 Readingfromfiles.........................................22
Exercise5.3.............................................25,30 simpleifstatement.......................................15
Exercise5.4...................................................31 statement........................................................6
Exercise5.5...................................................31 stop...............................................................15
Exercise5.6...................................................33 Style..............................................................14
Exercise5.7...................................................34 subroutine.....................................................35
Exercise6.1...................................................38 summation....................................................20
Exercise6.2...................................................39 Transposeofamatrix...................................40
Exercise6.3...................................................39 UserDefinedFunctions.................................38
Exercise7.1...................................................42 variable...........................................................6
Exercise7.2...................................................42 Writingtofiles..............................................23
Exercise7.3...................................................42

CopyrightJanetANicholson2011 45 fortrantutorial.com

You might also like