Copyright©JanetANicholson2011 1 fortrantutorial.com
IntroductiontoProgramming
usingFORTRAN95
Theseworksheetsaimtoprovideanintroductionto
programming.ThelanguagechosenforthisisFORTRAN95.This
isbecauseFORTRANisparticularlysuitableforscienceand
engineering;itisalsoverywidelyavailable.
Theskillsyouacquireworkingthroughthesenotescanbe
appliedtoanycomputinglanguage.Theconceptsyouwilllearn
aresharedincommonwitheveryothercomputinglanguage.
Thisdocumentandalltheexamplesmaybefoundonlineat:
/>
©JanetANicholson2011
Copyright©JanetANicholson2011 2 fortrantutorial.com
1 THEBASICS 3
1.1
AIMS 3
1.2 INSTALLFTN95PERSONALEDITION 3
1.3 YOURFIRSTPROGRAMMINGSESSION 3
1.4 PLATOAPROGRAMMINGE NVIRONMENT 3
1.5 RUNNINGYOURFIRSTFORTRAN95PROGRAM 4
1.6 PROGRAMSTRUCTURE 6
1.7 MOREONINPUTANDOUTPUT 6
1.8 MOREDATATYPES–INTEGERANDCHARACTER 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 IMPORTANTNOTE–TESTINGFORZERO 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 CONVERGENCE–EXITINGLOOPSONACONDITION 25
5 ARRAYSANDFORMATTEDI/O 27
5.1 AIMS 27
5.2 ARRAYS 2 7
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 REUSINGCODE–THESUBROUTINE 35
6.3 ARGUMENTSTOSUBROUTINES 36
6.4 USERDEFINEDFUNCTIONS 38
7 ADVANCEDTOPICS 40
7.1 AIMS 40
7.2 ARRAYFUNCTIONS 40
7.3 WRITINGREALPROGRAMSFLOWCHARTS 42
Copyright©JanetANicholson2011 3 fortrantutorial.com
1 TheBasics
1.1 Aims
Bytheendofthisworksheet,youwillbeableto:
CreateandrunaFORTRAN95program
Understandbasicprogramstructure
Starttodealwithprogrammingerrors
Starttounderstandreal,integerandcharactervariabletypes.
SaveacopyofyouroutputinWord.
1.2 InstallFTN95PersonalEdition
SearchforSilverfrostFTN5personaleditionorclickthislink
/>.
Downloadandinstallthesoftwareacceptingallthedefaults.
1.3 Yourfirstprogrammingsession
LocateanddoubleclickthePlato
icon
ClickFile,New
SelectFreeFormatFortranFile
ClickFile,SaveAs
Createadirectorycalledfortranprogramsandopenit
Typefirst.f95
1.4 Platoaprogrammingenvironment
Copyright©JanetANicholson2011 4 fortrantutorial.com
Platoisa"programmingenvironment".WithinPlato,youcancreateandeditprogramsandgetthem
torun.Plato'seditorisspecial–itunderstandsthesyntaxofvariousprogramminglanguages.Wetell
Platowhichlanguageweareusingwhenwecreateouremptyfileandsaveitwitha.f95(FO
RTRAN
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
Copyright©JanetANicholson2011 5 fortrantutorial.com
Clicktheblack,(theExecutebutton).
PlatowillgetFTN95tocheckyourprogramforerrors.Ifitfindsanyproblems,itwillgiveyou
thedetails.Ifyouhavetypedintheprogramexactlyasshownabove,anexecutablefilewill
begenerated(first.exe).Platowillthenautomaticallygetthepro
gramtostartexecuting.
Abannerwillappearforacoupleofsecondsandwillthendisappear(that"sthepricewe
havetopayforusingthefreesoftware)
Ablackconsolewindowwillappear.
PressReturntoclosethewindow.DonotclicktheXatthetopri
ghtofthewindow.
PlatocangetupsetifyoudonotpressReturntoclosethewindow,trythis…
Saveyourprogramfirst!
Runtheprogramagain(click)
ThistimeclicktheXatthetoprightofthewindowtoclos
eit.
Makeupyourownmindaboutwhichisthebetterwaytoclosethiswindowinfuture!
Copyright©JanetANicholson2011 6 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.Alltexttotherightofanexclamationmarkisignoredbyth
ecompiler.
Programmersusecommentstohelpthemrememberhowaprogramworks.Useof
appropriatecommentsinprogramsaidsunderstandingandisgoodpractice.
c) Variablesanswer, x and y areusedtostorefloatingpointnumbers–weindicate
thisbydeclaringthemasreal.
d) print *,outputstoth
escreen–theasteriskmeansusethedefaultnumberofdecimal
placeswhenthenumberiswrittentothescreen.
e) Wereadinformationfromthek eyboardandstorethevaluesin xandy.
f) Dosomearithmeticandstoretheanswerinanswer.
g) Outputtheresulttoth
escreen
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.
Copyright©JanetANicholson2011 7 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
/>
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.
Copyright©JanetANicholson2011 8 fortrantutorial.com
Correctthetwoerrors.
ClickExecute
Thereisnowonefurthererror,Platowillprovideayellowwarningalert.Watchthescreen
carefully!Thewindowwillcloseandthentheprogramwillstarttoexecute.Somethingis
notcorrecthowever…theprogramwill"hang".Itisactuallywaitingforyoutoinputavalue,
becauseoftheline
read*,c.Totheuseroftheprogram,thisisnotatallobvious–they
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,
thencompareyourprogramwiththeonecalledbu
gfixed.f95at
/>
1.8 MoreDatatypes–integerandcharacter
Sofar,wehaveonlyusedreal(floatingpointnumbers)inourprograms.Wecanalsospecifythat
numbersareintegerandcharacter.Programconvert,below,demonstratestheiruse.
Withinagivenrange,integersarealwaysrepresentedexactlywhereastheprecisionofrealnumbers
islimitedbythearchitectureofthemachine.Therealvariabletypegivesus6figurede
cimal
precision.(Ifthisdoesn'tseemenough–don'tworrywe'llcomebacklateronwhenweexaminehow
toincreasethenumberofdigitsofprecisioninSection4).
Charactervariablesholdstringsofcharacterslike
'A happy day was had by all'
'Yes'
'N'
'3 + 4 equals 7'
Copyright©JanetANicholson2011 9 fortrantutorial.com
Whenthecharactervariableisdeclared,weshowthemaximumlengththatthestringcanoccupyby
followingthenamebya*thenitsmaximumlength.Theexamplebelowhasamaximumlengthof10
charactersallowedforaperson'sname–thismightnotalwaysbeenough!Youhavetomakea
judgementher
e.
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
thelettersinth
erangei–n,alltheothersbeingreal.FORTRANstillallowsyoutodothisifwedon't
includetheline,implicitnone.Timehasshownthatoneofthecommonestreasonsforerrorina
programistheincorrectuseofvariables.
Alwaysuseimplicitno
neatthestartofeveryprogram.
Exercise1.4
Withtheprogramconvertinsection1.5asaguide,writeaprogramtotestouteverythingyou've
learnedsofar.Youmightincludedifferenttypesofvariables,forexamplereal,integer,and
character.Includeinputandoutputusingreadandprint.Anexamplemightbeaprogramthatasks
peoplequestio
ns,includingthingsliketheirageandnameandsoon.Itcould,forexample,printout
theiryearofbirthwithasuitablemessage.It'suptoyou,justuseyourimagination.
Copyright©JanetANicholson2011 10 fortrantutorial.com
1.9 SavingthecontentsofOutputWindow
Runyourlastprogramagain.Whentheblackoutputwindowopensrightclickonthe
Platoiconinthetopleftcorner
Clickonedit
ClickSelectall
Clickcopy
OpenanewdocumentinWordorNotepadandclickpaste.
Copyright©JanetANicholson2011 11 fortrantutorial.com
2 MakingDecisions
2.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Doarithmetic
StarttouseFORTRANintrinsicfunctions
Begintounderstandprogramflowandlogic
Knowhowtotestforzero–important!
Learnmoreaboutgoodprogrammingstyle
2.2 Assignment
Whenwestartprogramming,thesimilaritybetweenmathematicalequationsandFORTRAN
statementscanbeconfusing.
ConsiderthefollowingFORTRANstatements:
x = 2 Storethevalue2inmemorylocationx
y = 3 Storethevalue3inmemorylocationy
z = x + y Addthevaluesstoredinmemorylocation
xandyandstoretheres
ultinmemorylocationz
Inmathematics,“x=2”meansthatthevariablexisequalto2.InFORTRANitmeans“storethevalue
2inthememorylocationthatwehavegiventhenamex”.
Thesignificanceofthisismadeclearerbythefollowingequ
ationinmathematics:
x+y=z
Inmathematics,thismeansthatthelefthandsideoftheequationisequaltotherighthandside.
InFORTRAN,thisexpressionismeaningless:thereisnomemorylocation"x+y"andsoitwouldleadto
acompilererror.
Rule–therecanonlyeverbeONEvariablenameonthelefthandsideofanequalssign
Exercise2.1
Writeaprogramwhichreadsintwonumbersaandb.Gettheprogramtoswapthevaluesaroundso
thatthevaluethatwasinaisnowinb,andprintouttheresult.Hintyouneedtodeclareathird
variableforintermediatestorageofthedata.(Che
ckyourprogrambyexaminingprogramswap.f95at
/>
2.3 Arithmetic
Thearithmeticoperatorsare
+,- plusandminus
*,/ multiplyanddivide
** exponentiation(raisetothepower)
() brackets
TheorderofprecedenceinFORTRANisidenticaltothatofmathematics.
Unlikealgebra,theoperatormustalwaysbepresentxyisnotthesameasx*y
Whereoperationsareofequalprecedencetheyareevaluatedlefttoright
Consecutiveexponentiationsareevaluatedrighttoleft
Wecanoverridetheorderofevaluationbyuseofbrackets
Copyright©JanetANicholson2011 12 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:
1.
zx
yx
2. xyz
3. x
y
z
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 e
x
log(x) real real log
10
x
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
Copyright©JanetANicholson2011 13 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
Theboldedlinesintheaboveprogramarecalledif…endifstatements.Theyworklikethis:
if(conditionistrue)then
executethisline
andthis
andsoonuntilwegetto…
endif
ItfollowsthatiftheconditionisNOTtruethentheco
de'jumps'tothenextstatementfollowingthe
'endif'.Thestatementsbetweentheifandtheendifaredeliberatelyindented,thismakesthe
programeasiertoread.
Weusetwoconsecutiveequalssigns(nospaceinthemiddle)totestforequality.Compare
if (choice == 3) then
test
choice = 3 assignment
Copyright©JanetANicholson2011 14 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,endifthath
andlesthissituation.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
>= greaterth
anorequalto
Copyright©JanetANicholson2011 15 fortrantutorial.com
2.9 MultipleConditions
Supposeweneedtotestifxisgreaterthanyandyisgreaterthanz.Therearedifferentwaysofdoing
this:
if(x>y)then
if(y>z)then
dosomething
endif
endif
Thiscanalsobehandledbythefollowing:
if(x>y.an
d.y>z)then
dosomething
endif
Ifwewantedtocheckwhetheranumberwerelessthanagivenvalueorgreaterthanagivenvalue
wecouldwrite:
if(x<10.or.x>20)then
doso
mething
endif
Exercise2.4
Writeaprogramthatreadsanumberfromthekeyboard.Gettheprogramtodecidewhether:
thevalueofthenumberisgreaterthan0butlessthan1
orisg reate rthan1butlessthan10
orisoutside ofboththeseranges
Printoutasuitablemessagetoinformtheuser.
2.10 Thesimpleifstatement
Thereisasimpler,onelineformoftheifstatement.Saywejustwantedtoprintoutasimple
messagesuchas
print *, 'enter a positive number'
read *, num
if (num <0) stop
if (num < 10) print *, 'less than 10'
if (num > 10) print *, 'greater than 10'
print *,'It is a positive number'
noticethe.and.
noticethe.or.
Thissnippetalso
introducesauseful,
simplestatement
stop–itsimply
stopstheprogram.
Copyright©JanetANicholson2011 16 fortrantutorial.com
2.11 Importantnote–testingforzero
Supposethatyouwishtotestwhetherarealvariableiszero.Thetest
if (x = = 0) then ….
isnotasatisfactorytest.Althoughintegernumbersareheldexactly
bythecomputer,realnumbersar enot.
Thewayaroundthisistotestiftheabsolutevalueofthevariableislessthansomesmallpredefine
d
value.Forexample:
if (abs(x) < .000001) then
print *,’No zero values! Please enter another number’
read *, x
end if
Makesureyou
understandthis!
Copyright©JanetANicholson2011 17 fortrantutorial.com
3 Loops
3.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Understandmoreabouttheuseofrealandintegervariablesandhowtouseamixtureof
datatypesinexpressions
Understandhowtoreusecodebylooping
Knowhowtocontrolthenumberoftimesasectionofcodeisexecutedbyusingadoloop
3.2 Mixingvariabletypes
Exercise3.1
Copydivide.f95
program divide
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?FORTRANiskeepingth
eintegerpartoftheanswerandthrowingthe
restaway.
Makesureyouunderstandthis
thoroughly!
Copyright©JanetANicholson2011 18 fortrantutorial.com
Togetoverthisproblem,wehavetosignaltoFORTRANthatwewantittocalculatetherighthand
sideoftheexpressionusingrealarithmetic.Ifwewanttokeepxasintegerdatatype,wecouldre
writeourexpressionasfollows:
y=x/3.0
Thepresenceofarealnu
mberontherighthandsidecausestherighthandsideoftheexpressionto
beevaluatedusingfloatingpointarithmetic.
Actually,theproblemisevenmorecomplicated!Wherewehaveanexpressionlike
y=x*((2**i)/3)
wherexandyarerealandiisinteger,FO
RTRANcomputestheresultinstages:
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,wemightaswelluseacalculator…Nowwestarttotake
advantageofthepowerofthecomputer.
Exercise3.3
Copyprogramloop.f95
program loop
implicit none
integer :: i
do i=0,20
print *,i
end do
Copyright©JanetANicholson2011 19 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.
Loopsca
nalsodecrement:trythis
do i = 5,-5,-2
Exercise3.4
Usingadolooptogenerateintegervaluesofxbetween–10and10instepsof1,writeaprogram
thatconstructsatableofvaluesof
y=1.0/x
Whathappenedwhenxhadthevaluezero?Useanif,endiftotestfortheconditionthatgivesthe
incorrectvalue,andprintou
tanappropriatemessage.Compareyourresultwithdivbyzero.f95.
Divisionbyzeroisoneofthecommonestreasonsforaprogramtofail.
3.4 NestedDoLoops
Wewanttoconstructatableofvaluesforzwhere
z=x
y
forvaluesof xintherange1to2instepsof0.5and
yintherange1to2instepsof0.5
Workthroughthenextexercisewhichillustratesthis:
Copyright©JanetANicholson2011 20 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?
Theanswerwo
uldbe2.0.
Bearinginmindthedefinitionofanassignment,thestatement
x=x+1.0
means“add1.0tothevaluecurrentlystoredinmemorylocationxandthenstoretheresultin
memorylocationx”.
Reallyimportant!
Copyright©JanetANicholson2011 21 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'tsure–changethecodetoputthelinex=1.0insidetheloop–then
examinetheoutput.
Itisimportanttounderstandthatifweuseconstructionssuchasx=x+1.0,thenitisvitalto
initialisextosomevalue.Ifwedon't,itispossiblethatthevaluemightbesettoanyrandom
number.Runtheprogram,makeanoteofthefinalvalueofxthe
nputanexclamationmark
infrontofthex=1.0statementandruntheprogramagain.
Exercise3.7
Editthelinex=x+1.0inprogramincrement.f95,andchangeittox=x*i.Reruntheprogramand
examinetheoutput.Whatissignificantmathematicallyaboutthesequenceofnumbersthathasbeen
generated?
Copyright©JanetANicholson2011 22 fortrantutorial.com
4 UsingFilesandExtendingPrecision
4.1 Aims
Bytheendofthisworksheet,youwillbeableto:
Readfromandwritetofiles
Useextendedprecision
4.2 Readingfromfiles
Intherealworld,mostofthedataweuseforourprogramswillbekeptinfiles.Wejustneeda
modificationtothereadstatementthatwearealreadyfamiliarwithtodothis.
Thisprogramreads3numbersfromafilecalled'mydata.txt'intoanarray.UseWindowsNote
padto
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,itcoul
dbeanypositiveinteger).Toreadfromdevice10,wejustuseitasthefirst
argumentinthereadstatement.
Exercise4.1
UseNotepadtocreateafilecalledevenodd.txt.Inthefiletype10numbers,oneperline.Writea
programthatreadsdatafromevenodd.txtonelineatatime.Checkifeachnumberisevenoroddand
printoutasuitablemessage.Onewaytocheckifanumberisevenoroddistouseth
emodintrinsic
function,likethis…
if (mod(num,2)>0) then……
modreturnstheremainderofthefirstargumentdividedbythesecond.Ifthereturnvalueisgreater
thanzero,thenthenumbermustbeodd.Checkprogramevenodd.f95toseeifyouarecorrect.
Copyright©JanetANicholson2011 23 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'tbeputoffbytheoddl
ookingcode.Inpractice,thewayofsettingupthisextendedprecision,is
prettymuchthesameforeveryprogram.
Westatetheprecisionwewantbytheargumentp
integer, parameter :: ikind=selected_real_kind(p=15)
Copyright©JanetANicholson2011 24 fortrantutorial.com
inthiscase,15decimalplaces.ikindisanewdatatype–aparameter.FORTRANreturnsavalueto
theparameterikindthatwillbeadequatetoprovide15digitprecision.Thiscodewillworkonany
machineirrespectiveofthearchitecture.
Wedeclarethatthevariablesareusingext
endedprecisionby
real (kind=ikind) :: sum,x
Validvaluesforpare6,15and18.Thedefaultvalueforpis6.Ifyouaskformoreprecisionthan18
digits,thecompilerwillcomplainwithanerrormessage.Trychangingthevaluesofpandseewhat
effectthishasontheoutput.
NoteUnlikevariables,parametersmaynotchangeoncetheyaredeclared.
Ifwewanttouseconstantsinaprogramthatusesextendedprecision,wehavetotellFORTRANthat
theyarealsoextendedprecisionexplicitly.Thisleadstotheratherstrangesyntaxyoucanseeinthe
followingpro
gram.
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.I’llleavethistoyoutoexperimenttoensure
thatyoufullyunderstandtheimportanceofproperly
de
claringvariablesandtheuseofconstantsin
FORTRANprogramming.Asystematicapproachtoyourprogrammingwillreducetheriskoferrorsas
willrunningprogramswithtestdatathathaveknownsolutionssothatyoucanconfirmthatyour
programiserrorfree.
ThetroublewithPRINTisthattheprogrammerhasnocontroloverthenumberofdigitsoutput
irrespectiveoftheselectedprecision.
Lateronwe'llcomebacktothiswhenwelearnabouttheWRITEstatement,andoutput
formatting.
Copyright©JanetANicholson2011 25 fortrantutorial.com
4.5 Magnitudelimitations
Wehavealreadyobservedthatthereisalimitationoftheaccuracywithwhichwecandocalculations
inFORTRAN(andindeed,any,computerlanguage).Therearealsolimitationsonthemagnitudeofa
number.Thevariousmagnitudeandprecisionlimitsaresummarizedinthefollowingtable:
Valueofp
Decimalplaces Range
6 6(default)
10
38
15 15
10
307
18 18
10
4931
Exercise5.3
Toillustratetheselimitscopyfilemagnitude.f95andruntheprogram.Takeawhiletogetafeelfor
whatisgoingon.Tryinputtingvariousvaluesforthevariablemaxpower(eg400).Canyouconfirm
thatthetableaboveiscorrect?
Oneinterestingconstructis
print*,i,2.0_ikind**i
Here,wearetellingthecom
pilerthattherealconstant2.0isalsousingextendedprecision.Check
whathappensifyouselectextendedprecision(option3)andenteravalueofmaxpowerof400.See
whathappensifyourewritethelinetobe
print*,i,2.0**i
Runtheprogramagainanden
terthesamevalues.Canyouexplainwhatisgoingon?
4.6 Convergence–exitingloopsonacondition
Intheprogramextended.f95,wefoundthesumof
10
1
6
1
x
x
x
Itisusefultodetermineatwhatpointsuchsumsconvergetoasteadyvalue–otherwisewemay
makearbitraryassumptionsaboutthesummationrange.Clearly,apointwillbereached,withinthe
precisionrangethatcanbehandledonourcomputer,thattheterm
6
1
x
willbetoosmalltocontributetothesum.Atthispointweshouldexittheloopotherwisethe
programwilldomorecomputationthanisrequired.
Onewaytodothisistocomparethevalueofthevariablesumwithitspreviousvalue,andifthe
differencebetweenthetwoisverysmall,thenexitth
eloop.