Tải bản đầy đủ (.pdf) (45 trang)

introduce to programming using fortran 95

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (420.99 KB, 45 trang )

Copyright©JanetANicholson2011 1 fortrantutorial.com


IntroductiontoProgramming
usingFORTRAN95








Theseworksheetsaimtoprovideanintroductionto
programming.ThelanguagechosenforthisisFORTRAN95.This
isbecauseFORTRANisparticularlysuitableforscienceand
engineering;itisalsoverywidelyavailable.

Theskillsyouacquireworkingthroughthesenotescanbe
appliedtoanycomputinglanguage.Theconceptsyouwilllearn
aresharedincommonwitheveryothercomputinglanguage.


Thisdocumentandalltheexamplesmaybefoundonlineat:

/>

©JanetANicholson2011
Copyright©JanetANicholson2011 2 fortrantutorial.com
1 THEBASICS 3
1.1


 AIMS 3
1.2 INSTALLFTN95PERSONALEDITION 3
1.3 YOURFIRSTPROGRAMMINGSESSION 3
1.4 PLATOAPROGRAMMINGE NVIRONMENT 3
1.5 RUNNINGYOURFIRSTFORTRAN95PROGRAM 4
1.6 PROGRAMSTRUCTURE 6
1.7 MOREONINPUTANDOUTPUT 6
1.8 MOREDATATYPES–INTEGERANDCHARACTER 8
1.9 SAVINGTHECONTENTSOFOUTPUTWINDOW 10
2 MAKINGDECISIONS 11
2.1 AIMS 11
2.2 ASSIGNMENT 11
2.3 ARITHMETIC 11
2.4 INTRINSICFUNCTIONS 12
2.5 MAKINGDECISIONS 13
2.6 PROGRAMSTYLE 14
2.7 MOREONDECISIONMAKING 14
2.8 OTHERLOGICALOPERATORS 14
2.9 MULTIPLECONDITIONS 15
2.10 THESIMPLEIFSTATEMENT 15
2.11 IMPORTANTNOTE–TESTINGFORZERO 16
3 LOOPS 17
3.1 AIMS 17
3.2 MIXINGVARIABLETYPES 17
3.3 THEDOLOOP 18
3.4 NESTEDDOLOOPS 19
3.5 USINGLOOPSTODOSUMMATION 20
4 USINGFILESANDEXTENDINGPRECISION 22
4.1 AIMS 22
4.2 READINGFROMFILES 22

4.3 WRITINGTOFILES 23
4.4 EXTENDINGTHEPRECISION 23
4.5 MAGNITUDELIMITATIONS 25
4.6 CONVERGENCE–EXITINGLOOPSONACONDITION 25
5 ARRAYSANDFORMATTEDI/O 27
5.1 AIMS 27
5.2 ARRAYS 2 7
5.3 ARRAYMAGIC 29
5.4 MULTIDIMENSIONALARRAYS 30
5.5 FORMATTINGYOUROUTPUT 31
5.5.1 IntegerSpecification 32
5.5.2 FloatingpointSpecification 32
5.5.3 ExponentialSpecification 32
5.5.4 CharacterSpecification 33
5.6 IMPLIEDDOLOOPTOWRITEARRAYS 33
6 SUBROUTINESANDFUNCTIONS 35
6.1 AIMS 35
6.2 REUSINGCODE–THESUBROUTINE 35
6.3 ARGUMENTSTOSUBROUTINES 36
6.4 USERDEFINEDFUNCTIONS 38
7 ADVANCEDTOPICS 40
7.1 AIMS 40
7.2 ARRAYFUNCTIONS 40
7.3 WRITINGREALPROGRAMSFLOWCHARTS 42
Copyright©JanetANicholson2011 3 fortrantutorial.com

1 TheBasics
1.1 Aims
Bytheendofthisworksheet,youwillbeableto:
 CreateandrunaFORTRAN95program

 Understandbasicprogramstructure
 Starttodealwithprogrammingerrors
 Starttounderstandreal,integerandcharactervariabletypes.
 SaveacopyofyouroutputinWord.

1.2 InstallFTN95PersonalEdition
 SearchforSilverfrostFTN5personaleditionorclickthislink
/>.
 Downloadandinstallthesoftwareacceptingallthedefaults.
1.3 Yourfirstprogrammingsession

 LocateanddoubleclickthePlato
icon
 ClickFile,New
 SelectFreeFormatFortranFile
 ClickFile,SaveAs
 Createadirectorycalledfortranprogramsandopenit
 Typefirst.f95

1.4 Platoaprogrammingenvironment

Copyright©JanetANicholson2011 4 fortrantutorial.com
Platoisa"programmingenvironment".WithinPlato,youcancreateandeditprogramsandgetthem
torun.Plato'seditorisspecial–itunderstandsthesyntaxofvariousprogramminglanguages.Wetell
Platowhichlanguageweareusingwhenwecreateouremptyfileandsaveitwitha.f95(FO
RTRAN
95)extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable
tocheckthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsaboutusinga
colourcodetodistinguishbetweenthevariouselementsofthelanguage.
Alwaysensurethatyourprogramfileshavea.f95extension

1.5 RunningyourfirstFORTRAN95Program


Exercise1.1
 Typeinthefollowingexactlyasshown:
 !My first program
program first
print *,'This is my first program'
end program first

Copyright©JanetANicholson2011 5 fortrantutorial.com


 Clicktheblack,(theExecutebutton).
 PlatowillgetFTN95tocheckyourprogramforerrors.Ifitfindsanyproblems,itwillgiveyou
thedetails.Ifyouhavetypedintheprogramexactlyasshownabove,anexecutablefilewill
begenerated(first.exe).Platowillthenautomaticallygetthepro
gramtostartexecuting.
 Abannerwillappearforacoupleofsecondsandwillthendisappear(that"sthepricewe
havetopayforusingthefreesoftware)
 Ablackconsolewindowwillappear.
 PressReturntoclosethewindow.DonotclicktheXatthetopri
ghtofthewindow.

PlatocangetupsetifyoudonotpressReturntoclosethewindow,trythis…
 Saveyourprogramfirst!
 Runtheprogramagain(click)
 ThistimeclicktheXatthetoprightofthewindowtoclos
eit.
 Makeupyourownmindaboutwhichisthebetterwaytoclosethiswindowinfuture!



Copyright©JanetANicholson2011 6 fortrantutorial.com
1.6 ProgramStructure
Examinethefollowingshortprogram:
program sum !a:nameofprogram 
!an example of program structure !b:acomment 
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:endofprogram

Thereareanumberofgeneralpointshere:
 Theprogramismadeupofanumberoflines.Eachlineiscalledastatement.
 Eachstatementismadeupof
 variablenamese.g.answer, x, y
 operatorse.g.+,-etc
 keywordse.g.read, print
 Thestatementsareexecutedsequentially.

Let'sbreaktheprogramdown,linebyline:
a) Thenameoftheprogram.Keepitreasonablyshortandmeaningful.
b) Acommentexplainingthepurposeoftheprogram.Commentsareindicatedbyan
exclamationmark.Alltexttotherightofanexclamationmarkisignoredbyth
ecompiler.
Programmersusecommentstohelpthemrememberhowaprogramworks.Useof
appropriatecommentsinprogramsaidsunderstandingandisgoodpractice.

c) Variablesanswer, x and y areusedtostorefloatingpointnumbers–weindicate
thisbydeclaringthemasreal.
d) print *,outputstoth
escreen–theasteriskmeansusethedefaultnumberofdecimal
placeswhenthenumberiswrittentothescreen.
e) Wereadinformationfromthek eyboardandstorethevaluesin xandy.
f) Dosomearithmeticandstoretheanswerinanswer.
g) Outputtheresulttoth
escreen
h) Concludetheprogram


1.7 MoreonInputandOutput
Exercise1.2
 Openanewfileandcallitio.f95.
 Typeinthefollowingprogram:
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
 Executeitbypressing
 YoucanenterthenumbersoneatatimeandpresstheEnterkeyeachtime.
 Executetheprogramagain
 Thistimetypeallthreenumbersononelineseparatedbycommas.
Copyright©JanetANicholson2011 7 fortrantutorial.com
Lookattheprintstatement
print *, 'the values you typed are for z,y,x are: ',z,y,x
Inthisstatement,weareoutputtingfourseparatethings,aliteralstringofcharacters,

'the values you typed are for z,y,x are: '
andthevariablesz,y,andx.Wemayoutputseveralitemsatonetime,providedtheyareseparated
bycommas.

Exercise1.3
Thefollowingprogramhasanumberoferrors.
 Createanewfilecalledbug.f95andthentypeinthefollowingprogramexactlyasshown.
 Youcanalsodownloadthisfilefrom
/>
program bug
this program is full of errors
real :: a,b,c
a = b + c
read *,c
print *,a
end program simple
Thecompilerwillreporttwoerrormessageswhenitattemptstocompile.Clickonthedetailsbutton.
Eacherrorgeneratesamessage.


Doubleclickingonthemessagewill
takeyoutothelineintheprogramwherethefaultoccurs.



Copyright©JanetANicholson2011 8 fortrantutorial.com

 Correctthetwoerrors.
 ClickExecute
 Thereisnowonefurthererror,Platowillprovideayellowwarningalert.Watchthescreen

carefully!Thewindowwillcloseandthentheprogramwillstarttoexecute.Somethingis
notcorrecthowever…theprogramwill"hang".Itisactuallywaitingforyoutoinputavalue,
becauseoftheline
read*,c.Totheuseroftheprogram,thisisnotatallobvious–they
mayhavethoughtthattheprogramhascrashed!
 Typeinanumberthenpressenter
 Theprogramreturnsanstrangevalue.Thisisan"executiontime"error.
 Weneedtofindoutwhatthewarningmessagewas.Clickthe"compile"button(totheright
ofthebinoculars).Thenclickthe"details"button.Platowilltellyouthatthevariablebhas
notbeengivenavalue.
 Correcttheprogramtogivebavalue,andthenexecutetheprogramagain.
 Thereisstillaproblem.Thistime,itisaproblemwiththeprogram'slogic.

NeedaHint?Theprogramstatementsareexecutedsequentially.
a=b+c
read *, c
print *, a
Thestatementa=b+cdoesn'tmakesense,asatthisstageoftheprogram,wehaven'tyetgivena
valuetoc.

Importantpointstonote
 Therearetwotypesoferrorsassociatedwiththisprogram:compilererrorsandruntime
errors.
 Theprogramisalsouserunfriendly.Theprogramwaitsforinputwithouttellingtheuser
whatisneeded.
Fixtheruntimeerrorby:

 readinavalueforb
 correcttheorderofthestatements
 maketheprogrammoreuserfriendly,


thencompareyourprogramwiththeonecalledbu
gfixed.f95at

/>

1.8 MoreDatatypes–integerandcharacter
Sofar,wehaveonlyusedreal(floatingpointnumbers)inourprograms.Wecanalsospecifythat
numbersareintegerandcharacter.Programconvert,below,demonstratestheiruse.

Withinagivenrange,integersarealwaysrepresentedexactlywhereastheprecisionofrealnumbers
islimitedbythearchitectureofthemachine.Therealvariabletypegivesus6figurede
cimal
precision.(Ifthisdoesn'tseemenough–don'tworrywe'llcomebacklateronwhenweexaminehow
toincreasethenumberofdigitsofprecisioninSection4).

Charactervariablesholdstringsofcharacterslike
'A happy day was had by all'
'Yes'
'N'
'3 + 4 equals 7'
Copyright©JanetANicholson2011 9 fortrantutorial.com
Whenthecharactervariableisdeclared,weshowthemaximumlengththatthestringcanoccupyby
followingthenamebya*thenitsmaximumlength.Theexamplebelowhasamaximumlengthof10
charactersallowedforaperson'sname–thismightnotalwaysbeenough!Youhavetomakea
judgementher
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

NOTEtheinclusionoftheline

implicit none


Byincludingitinyourprogram,FORTRANwillcheckthatyouhaveproperlydeclaredallyourvariable
types.Inthebadolddaysofprogramming,declarationofvariableswasthoughttobeunnecessary
andtheoldFORTRANcompilersusedanimplicitconventionthatintegershavenamesstartingwith
thelettersinth
erangei–n,alltheothersbeingreal.FORTRANstillallowsyoutodothisifwedon't
includetheline,implicitnone.Timehasshownthatoneofthecommonestreasonsforerrorina
programistheincorrectuseofvariables.


Alwaysuseimplicitno
neatthestartofeveryprogram.




Exercise1.4
Withtheprogramconvertinsection1.5asaguide,writeaprogramtotestouteverythingyou've
learnedsofar.Youmightincludedifferenttypesofvariables,forexamplereal,integer,and
character.Includeinputandoutputusingreadandprint.Anexamplemightbeaprogramthatasks
peoplequestio
ns,includingthingsliketheirageandnameandsoon.Itcould,forexample,printout
theiryearofbirthwithasuitablemessage.It'suptoyou,justuseyourimagination.
Copyright©JanetANicholson2011 10 fortrantutorial.com

1.9 SavingthecontentsofOutputWindow
Runyourlastprogramagain.Whentheblackoutputwindowopensrightclickonthe
Platoiconinthetopleftcorner



 Clickonedit
 ClickSelectall
 Clickcopy
 OpenanewdocumentinWordorNotepadandclickpaste.




Copyright©JanetANicholson2011 11 fortrantutorial.com
2 MakingDecisions
2.1 Aims
Bytheendofthisworksheet,youwillbeableto:
 Doarithmetic
 StarttouseFORTRANintrinsicfunctions
 Begintounderstandprogramflowandlogic

 Knowhowtotestforzero–important!
 Learnmoreaboutgoodprogrammingstyle
2.2 Assignment
Whenwestartprogramming,thesimilaritybetweenmathematicalequationsandFORTRAN
statementscanbeconfusing.
ConsiderthefollowingFORTRANstatements:

 x = 2 Storethevalue2inmemorylocationx
 y = 3 Storethevalue3inmemorylocationy
 z = x + y Addthevaluesstoredinmemorylocation
 xandyandstoretheres
ultinmemorylocationz 
Inmathematics,“x=2”meansthatthevariablexisequalto2.InFORTRANitmeans“storethevalue
2inthememorylocationthatwehavegiventhenamex”.

Thesignificanceofthisismadeclearerbythefollowingequ
ationinmathematics:

 x+y=z

Inmathematics,thismeansthatthelefthandsideoftheequationisequaltotherighthandside.
InFORTRAN,thisexpressionismeaningless:thereisnomemorylocation"x+y"andsoitwouldleadto
acompilererror.


Rule–therecanonlyeverbeONEvariablenameonthelefthandsideofanequalssign


Exercise2.1
Writeaprogramwhichreadsintwonumbersaandb.Gettheprogramtoswapthevaluesaroundso

thatthevaluethatwasinaisnowinb,andprintouttheresult.Hintyouneedtodeclareathird
variableforintermediatestorageofthedata.(Che
ckyourprogrambyexaminingprogramswap.f95at
/>
2.3 Arithmetic
Thearithmeticoperatorsare
+,- plusandminus
*,/ multiplyanddivide
** exponentiation(raisetothepower)
() brackets 
 TheorderofprecedenceinFORTRANisidenticaltothatofmathematics.
 Unlikealgebra,theoperatormustalwaysbepresentxyisnotthesameasx*y
 Whereoperationsareofequalprecedencetheyareevaluatedlefttoright
 Consecutiveexponentiationsareevaluatedrighttoleft
 Wecanoverridetheorderofevaluationbyuseofbrackets
Copyright©JanetANicholson2011 12 fortrantutorial.com

Exercise2.2
Thefollowingprogramisanexampleoftheuseofarithmetic.
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
Exploretheuseofarithmeticoperatorsbymodifyingprogramcalculate.Useittocalculatethevalues:


1.
zx
yx



2. xyz
3. x
y
z

2.4 IntrinsicFunctions
FORTRANisespeciallyusefulformathematicalcomputationbecauseofitsrichlibraryofinbuilt
functions(intrinsicfunctions).Weshallmentionafewbrieflyhere:

functionname typeofargument typeofresult 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 absolutevalue
sqrt(x)  real  real squareroot
exp(x)  real  real e
x

log(x)  real  real log
10
x


Trigonometricfunctionsarecalculatedinradians(1radian=180/Pidegrees).

Thereare,ofcourse,manymore,andthislistdoesn'tcoverallFORTRANvariabletypes.Thefollowing
exampleshowstheuseofsomeoftheinbuiltfunctions.

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©JanetANicholson2011 13 fortrantutorial.com
2.5 MakingDecisions
Sofar,ourprogramshaveworkedaslittlemorethanbasiccalculators.Thepowerofprogramming
comesinwhenwehavetomakedecisions.Copytheexampleprogram,test.f95,toyourownfile
space.Seeifyoucanunderstandwhatisgoingon.
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
Theboldedlinesintheaboveprogramarecalledif…endifstatements.Theyworklikethis:

 if(conditionistrue)then
executethisline
andthis
andsoonuntilwegetto…
endif

ItfollowsthatiftheconditionisNOTtruethentheco
de'jumps'tothenextstatementfollowingthe
'endif'.Thestatementsbetweentheifandtheendifaredeliberatelyindented,thismakesthe

programeasiertoread.

Weusetwoconsecutiveequalssigns(nospaceinthemiddle)totestforequality.Compare
if (choice == 3) then
test
choice = 3 assignment


Copyright©JanetANicholson2011 14 fortrantutorial.com
Exercise2.3
Examineprogramtestabove.Theline

print *,'result = ',answer
isrepeatedseveraltimes.Isthisagoodidea?Canyoumodifytheprogramtomakeitmoreefficient?


2.6 ProgramStyle
Agoodprogram:

 Usescommentsappropriatelytoexplainwhatishappening.
 Usesindentationtomaketheprogrameasiertoread.
 Usesmeaningfulvariablenames.
 Usessensiblepromptstolettheuserknowwhatisgoingon.
 Usesimplicit noneatthestartofeveryprogram.
 Isefficient!

Ifyouwanttogetmaximummarksforyourassignmentskeeptheabovepointsfirmlyinmind.Itis
notenoughjusttogetaprogramtowork!



2.7 Moreondecisionmaking
Inourtest.f95above,therewasaproblemiftheuserenteredavaluethatwasn'tcateredforbythe
program.

Whathappensiftheuserdoesn'tenteroneofthevalues1,2or3?

Wearegoingtolookatanewstructure,calledif,else,endifthath
andlesthissituation.Examinethe
followingcodesnippet:

if(choice==1)then
dosomething
elseif(choice==2)then
dosomethingelse
else
dothisifnothingelsesatisfiestheconditions
endif


2.8 Otherlogicaloperators
Sofar,allourtestshavebeenforequality.Thereareseveraltestswecanmake:

 ==  equalto(thereisnospacebetweentheequalssigns)
 /= notequalto
 < lessthan
 <= lessthanorequalto
 > greaterthan
 >= greaterth
anorequalto
Copyright©JanetANicholson2011 15 fortrantutorial.com


2.9 MultipleConditions

Supposeweneedtotestifxisgreaterthanyandyisgreaterthanz.Therearedifferentwaysofdoing
this:


 if(x>y)then
if(y>z)then
dosomething
endif
 endif

Thiscanalsobehandledbythefollowing:

 if(x>y.an
d.y>z)then
dosomething
 endif

Ifwewantedtocheckwhetheranumberwerelessthanagivenvalueorgreaterthanagivenvalue
wecouldwrite:

 if(x<10.or.x>20)then
doso
mething
 endif

Exercise2.4
Writeaprogramthatreadsanumberfromthekeyboard.Gettheprogramtodecidewhether:


 thevalueofthenumberisgreaterthan0butlessthan1
 orisg reate rthan1butlessthan10
 orisoutside ofboththeseranges

Printoutasuitablemessagetoinformtheuser.

2.10 Thesimpleifstatement
Thereisasimpler,onelineformoftheifstatement.Saywejustwantedtoprintoutasimple
messagesuchas
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'

noticethe.and.
noticethe.or.
Thissnippetalso
introducesauseful,
simplestatement
stop–itsimply
stopstheprogram.
Copyright©JanetANicholson2011 16 fortrantutorial.com

2.11 Importantnote–testingforzero
Supposethatyouwishtotestwhetherarealvariableiszero.Thetest

if (x = = 0) then ….


isnotasatisfactorytest.Althoughintegernumbersareheldexactly
bythecomputer,realnumbersar enot.

Thewayaroundthisistotestiftheabsolutevalueofthevariableislessthansomesmallpredefine
d
value.Forexample:
if (abs(x) < .000001) then
print *,’No zero values! Please enter another number’
read *, x
end if






Makesureyou
understandthis!
Copyright©JanetANicholson2011 17 fortrantutorial.com
3 Loops
3.1 Aims
Bytheendofthisworksheet,youwillbeableto:
 Understandmoreabouttheuseofrealandintegervariablesandhowtouseamixtureof
datatypesinexpressions
 Understandhowtoreusecodebylooping
 Knowhowtocontrolthenumberoftimesasectionofcodeisexecutedbyusingadoloop





3.2 Mixingvariabletypes
Exercise3.1

Copydivide.f95

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

Andrunit.Thisprogramproducesthefollowingoutput:

0.00000
Somethingoddishappening.Theproblemistheline:

 y=x/3

FORTRANevaluatestherighthandsideoftheassignmentfirstusingintegerarithmetic,because
bothxand3areinteger.1dividedby3cannotbestoredasaninteger
,andsothevalue0isreturned.
Theresult,0,isthenconvertedtoarealnumberandtheassignedtoy.

Replacethelineinprogramdivide

x = 1 by

x = 10
Youroutputshouldnowbe:

3.00000
Canyouseewhatishappening?FORTRANiskeepingth
eintegerpartoftheanswerandthrowingthe
restaway.

Makesureyouunderstandthis
thoroughly!
Copyright©JanetANicholson2011 18 fortrantutorial.com
Togetoverthisproblem,wehavetosignaltoFORTRANthatwewantittocalculatetherighthand
sideoftheexpressionusingrealarithmetic.Ifwewanttokeepxasintegerdatatype,wecouldre
writeourexpressionasfollows:

 y=x/3.0

Thepresenceofarealnu
mberontherighthandsidecausestherighthandsideoftheexpressionto
beevaluatedusingfloatingpointarithmetic.

Actually,theproblemisevenmorecomplicated!Wherewehaveanexpressionlike

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

wherexandyarerealandiisinteger,FO
RTRANcomputestheresultinstages:

Firstitcalculates(2**i)/3andevaluatesitasanintegernumber,thenmultipliestheresultbyxand
evaluatesitasreal.


Exercise3.2
Copycheck.f95toyourcomputer.


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

…andexamineitsoutput.Makesureyouunderstandwhythisishappening.
3.3 Thedoloop
Unlessweareabletoreexecutecode,wemightaswelluseacalculator…Nowwestarttotake
advantageofthepowerofthecomputer.


Exercise3.3
Copyprogramloop.f95

program loop
implicit none
integer :: i

do i=0,20
print *,i
end do
Copyright©JanetANicholson2011 19 fortrantutorial.com
end program loop

Runtheprogram.Itprintsoutthenumbersfrom0to20instepsof1.

Note:
 iiscalledaloopcounter.Inthisexample,ithasastartvalueofzero.
 Allthestatementswithinthedoandenddoareexecuted.Inthisexamplethereisjustthe
onestatement,ieprint.
 Eachtimethestatementsareexecuted,theloopcounter,i,isincrementedby1.
 Whenthevalueofiis20,theloopterminates,andtheprogramresumesaftertheenddo.

Changethedostatementinprogramloopasfollows:

do i = 50,70,2

Runtheprogram.Whathappens?

Thethirdargumentinthedostatement,istheincrementstep.Ifomitted,thevalueistakenas1.

Loopsca
nalsodecrement:trythis

do i = 5,-5,-2


Exercise3.4


Usingadolooptogenerateintegervaluesofxbetween–10and10instepsof1,writeaprogram
thatconstructsatableofvaluesof

y=1.0/x

Whathappenedwhenxhadthevaluezero?Useanif,endiftotestfortheconditionthatgivesthe
incorrectvalue,andprintou
tanappropriatemessage.Compareyourresultwithdivbyzero.f95.


Divisionbyzeroisoneofthecommonestreasonsforaprogramtofail.



3.4 NestedDoLoops
Wewanttoconstructatableofvaluesforzwhere

 z=x
y


forvaluesof xintherange1to2instepsof0.5and
 yintherange1to2instepsof0.5

Workthroughthenextexercisewhichillustratesthis:





Copyright©JanetANicholson2011 20 fortrantutorial.com
Exercise3.5
Copyprogramxytab.f95toyourfilespace.


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


Examineitsoutput.Noticetheuseofthefirstprinttogiveaheadingtothetable.


3.5 Usingloopstodosummation
Earlieron,wediscussedtheideaofassignments.

 x=1.0

meansstorethevalue1.0inthememorylocationcalledx.


Ifwehadthefollowingcode:

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

Canyouguesswhatvaluewouldbeprintedoutforx?

Theanswerwo
uldbe2.0.



Bearinginmindthedefinitionofanassignment,thestatement

 x=x+1.0

means“add1.0tothevaluecurrentlystoredinmemorylocationxandthenstoretheresultin
memorylocationx”.

Reallyimportant!
Copyright©JanetANicholson2011 21 fortrantutorial.com

Exercise3.6
Copyfileincrement.f95toyourfilespaceandexamineitsoutput.
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

 Notecarefullythatwehavesettheinitialvalueofxoutsideofthedoloop.Whyhavewe
donethis?Ifyouaren'tsure–changethecodetoputthelinex=1.0insidetheloop–then
examinetheoutput.
 Itisimportanttounderstandthatifweuseconstructionssuchasx=x+1.0,thenitisvitalto
initialisextosomevalue.Ifwedon't,itispossiblethatthevaluemightbesettoanyrandom
number.Runtheprogram,makeanoteofthefinalvalueofxthe
nputanexclamationmark
infrontofthex=1.0statementandruntheprogramagain.

Exercise3.7
Editthelinex=x+1.0inprogramincrement.f95,andchangeittox=x*i.Reruntheprogramand
examinetheoutput.Whatissignificantmathematicallyaboutthesequenceofnumbersthathasbeen
generated?

Copyright©JanetANicholson2011 22 fortrantutorial.com
4 UsingFilesandExtendingPrecision
4.1 Aims
Bytheendofthisworksheet,youwillbeableto:
 Readfromandwritetofiles
 Useextendedprecision
4.2 Readingfromfiles
Intherealworld,mostofthedataweuseforourprogramswillbekeptinfiles.Wejustneeda
modificationtothereadstatementthatwearealreadyfamiliarwithtodothis.
Thisprogramreads3numbersfromafilecalled'mydata.txt'intoanarray.UseWindowsNote

padto
createsuchafileforyourself,orcopythefilefrommydata.txtwhichisonthewebsite.
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
Thenewmaterialherearethelines
open(10,file='mydata.txt')
read(10,*) x,y,z
Theopenstatementlinksthefilecalled'mydata.txt'withaninputdevicenumbered10(itdoesn't
havetobe10,itcoul
dbeanypositiveinteger).Toreadfromdevice10,wejustuseitasthefirst
argumentinthereadstatement.

Exercise4.1
UseNotepadtocreateafilecalledevenodd.txt.Inthefiletype10numbers,oneperline.Writea
programthatreadsdatafromevenodd.txtonelineatatime.Checkifeachnumberisevenoroddand
printoutasuitablemessage.Onewaytocheckifanumberisevenoroddistouseth
emodintrinsic
function,likethis…

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

modreturnstheremainderofthefirstargumentdividedbythesecond.Ifthereturnvalueisgreater
thanzero,thenthenumbermustbeodd.Checkprogramevenodd.f95toseeifyouarecorrect.


Copyright©JanetANicholson2011 23 fortrantutorial.com

4.3 Writingtofiles
Thisisasimilarideatoreadingfromfiles.Weneedanewstatement,though,insteadofprint,weuse
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
Exercise4.2
Writeaprogramwhichreadsinnumbersfromafileoneatatime.Ifthenumberispositive,itshould
storeitinafilecalled'positive.txt'andnegativenumbersinafilecalled'negative.txt'.

4.4 Extendingtheprecision
Sofar,wehaveusedtwotypesofvariables,realandinteger.Theproblemsofar,asyouwillhave
noticedonoutput,isthatweareextremelylimitedbythenumberofsignificantdigitsthatare
availableforcomputation.Clearly,whenwearedealingwithiterativeprocesses,thiswillleadrapidly
toerrors.Wecan
,however,extendtheprecisionavailablefromthesingleprecisiondefault,which
givesus6figuredecimalprecisionto15figuresbyusinganewspecificationforrealnumbers.
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

producesthefollowingoutput:
1.01734306196
Don'tbeputoffbytheoddl
ookingcode.Inpractice,thewayofsettingupthisextendedprecision,is
prettymuchthesameforeveryprogram.
Westatetheprecisionwewantbytheargumentp
integer, parameter :: ikind=selected_real_kind(p=15)
Copyright©JanetANicholson2011 24 fortrantutorial.com
inthiscase,15decimalplaces.ikindisanewdatatype–aparameter.FORTRANreturnsavalueto
theparameterikindthatwillbeadequatetoprovide15digitprecision.Thiscodewillworkonany
machineirrespectiveofthearchitecture.
Wedeclarethatthevariablesareusingext
endedprecisionby
real (kind=ikind) :: sum,x
Validvaluesforpare6,15and18.Thedefaultvalueforpis6.Ifyouaskformoreprecisionthan18
digits,thecompilerwillcomplainwithanerrormessage.Trychangingthevaluesofpandseewhat
effectthishasontheoutput.







NoteUnlikevariables,parametersmaynotchangeoncetheyaredeclared.
Ifwewanttouseconstantsinaprogramthatusesextendedprecision,wehavetotellFORTRANthat
theyarealsoextendedprecisionexplicitly.Thisleadstotheratherstrangesyntaxyoucanseeinthe
followingpro
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


Youshouldrunthisprogramforyourselfandthinkcarefullyaboutitsimplications.Thisprogram
demonstrateshoweasyitistogetcalculationswrong.I’llleavethistoyoutoexperimenttoensure
thatyoufullyunderstandtheimportanceofproperly
de
claringvariablesandtheuseofconstantsin
FORTRANprogramming.Asystematicapproachtoyourprogrammingwillreducetheriskoferrorsas
willrunningprogramswithtestdatathathaveknownsolutionssothatyoucanconfirmthatyour
programiserrorfree.
ThetroublewithPRINTisthattheprogrammerhasnocontroloverthenumberofdigitsoutput
irrespectiveoftheselectedprecision.

Lateronwe'llcomebacktothiswhenwelearnabouttheWRITEstatement,andoutput
formatting.
Copyright©JanetANicholson2011 25 fortrantutorial.com
4.5 Magnitudelimitations
Wehavealreadyobservedthatthereisalimitationoftheaccuracywithwhichwecandocalculations
inFORTRAN(andindeed,any,computerlanguage).Therearealsolimitationsonthemagnitudeofa
number.Thevariousmagnitudeandprecisionlimitsaresummarizedinthefollowingtable:


 Valueofp
Decimalplaces Range
6 6(default)

10
38

 15 15


10
307
 18 18

10
4931

Exercise5.3
Toillustratetheselimitscopyfilemagnitude.f95andruntheprogram.Takeawhiletogetafeelfor
whatisgoingon.Tryinputtingvariousvaluesforthevariablemaxpower(eg400).Canyouconfirm
thatthetableaboveiscorrect?

Oneinterestingconstructis

print*,i,2.0_ikind**i

Here,wearetellingthecom
pilerthattherealconstant2.0isalsousingextendedprecision.Check
whathappensifyouselectextendedprecision(option3)andenteravalueofmaxpowerof400.See
whathappensifyourewritethelinetobe

print*,i,2.0**i

Runtheprogramagainanden
terthesamevalues.Canyouexplainwhatisgoingon?
4.6 Convergence–exitingloopsonacondition
Intheprogramextended.f95,wefoundthesumof





10
1
6
1
x
x
x

Itisusefultodetermineatwhatpointsuchsumsconvergetoasteadyvalue–otherwisewemay
makearbitraryassumptionsaboutthesummationrange.Clearly,apointwillbereached,withinthe
precisionrangethatcanbehandledonourcomputer,thattheterm
6
1
x

willbetoosmalltocontributetothesum.Atthispointweshouldexittheloopotherwisethe
programwilldomorecomputationthanisrequired.

Onewaytodothisistocomparethevalueofthevariablesumwithitspreviousvalue,andifthe
differencebetweenthetwoisverysmall,thenexitth
eloop.


×