You are on page 1of 29

RichardKass

Winter2004

APhysics416FortranTutorial
(basedontheinformationat:http://macams1.bo.infn.it/tutorial/)

1. WhatisFortran?

2. Fortranbasics

3. Variables,declarations,andtypes

4. Expressionsandassignment

5. Logicalexpressions

6. Theifstatements

7. Loops

8. Arrays

9. Subprograms

10. RandomnumbersandMonteCarlosimulations

11. Simpleinputandoutput

12. Formatstatements

13. FileI/O

14. Commonblocks

15. dataandblockdata

16. Debugging

17. RunningFortranonthePhysicsDepartmentsVAX(OHSTPY)computer

18. AsampleFortranprogramforLab1
1.WhatisFortran?
Fortranisageneralpurposeprogramminglanguage,mainlyintendedformathematicalcomputationsin
science applications (e.g. physics). Fortran is an acronym for FORmula TRANslation, and was
originallycapitalizedasFORTRAN.However,followingthecurrenttrendtoonlycapitalizethefirst
letterinacronyms,wewillcallitFortran.Fortranwasthefirsthighlevelprogramminglanguage.The
workonFortranstartedinthe1950'satIBMandtherehavebeenmanyversionssince.Byconvention,a
Fortranversionisdenotedbythelasttwodigitsoftheyearthestandardwasproposed.Thuswehave
Fortran66,Fortran77andFortran90(95).

The most common Fortran version today is still Fortran 77, although Fortran 90 is growing in
popularity.Fortran95isarevisedversionofFortran90whichisexpectedtobeapprovedbyANSIsoon
(1996).TherearealsoseveralversionsofFortranaimedatparallelcomputers.Themostimportantone
isHighPerformanceFortran(HPF),whichisadefactostandard.

UsersshouldbeawarethatmostFortran77compilersallowasupersetofFortran77,i.e.theyallow
nonstandardextensions.InthistutorialwewillemphasizestandardANSIFortran77.

WhylearnFortran?
Fortranisthedominantprogramminglanguageusedinscientificapplications.Itisthereforeimportant
forphysics(orengineering)studentstobeabletoreadandmodifyFortrancode.Fromtimetotime,so
calledexpertspredictthatFortranwillrapidlyfadeinpopularityandsoonbecomeextinct.Thismay
actuallyhappenasC(orC++)israpidlygrowinginpopularity.However,previouspredictionsofthe
downfallofFortranhavealways beenwrong.Fortran is themostenduringcomputer programming
languageinhistory.OneofthemainreasonsFortranhassurvivedandwillsurviveissoftwareinertia.
Onceacompanyhasspentmanypeopleyearsandperhapsmillionsofdollarsonasoftwareproduct,it
isunlikelytotrytotranslatethesoftwaretoadifferentlanguage.Reliablesoftwaretranslationisavery
difficulttaskandtheres40yearsofFortrancodetoreplace!

Portability
A major advantage Fortran has is that it is standardized by ANSI (American National Standards
Institute)andISO(InternationalStandardsOrganization).Consequently,ifyourprogramiswrittenin
ANSI Fortran 77 then it will run on any computer that has a Fortran 77 compiler. Thus, Fortran
programsareportableacrosscomputerplatforms

2.Fortran77Basics
AFortranprogramisjustasequenceoflinesoftext.Thetexthastofollowacertainsyntaxtobeavalid
Fortranprogram.Westartbylookingatasimpleexamplewherewecalculatetheareaofacircle:

programcircle
realr,area
cThisprogramreadsarealnumberrandprints
ctheareaofacirclewithradiusr.
write(*,*)'Giveradiusr:'
read(*,*)r
area=3.14159*r*r
write(*,*)'Area=',area
stop
end
Thelinesthatbeginwitha"c"arecommentsandhavenopurposeotherthantomaketheprogrammore
readableforhumans.Originally,allFortranprogramshadtobewritteninalluppercaseletters.Most
peoplenowwritelowercasesincethisismorelegible.

Programorganization
AFortranprogramgenerallyconsistsofamainprogram(ordriver)andpossiblyseveralsubprograms
(orproceduresorsubroutines).Fornowwewillassumeallthestatementsareinthemainprogram;
subprogramswillbetreatedlater.Thestructureofamainprogramis:

programname
declarations
statements
stop
end
Inthis tutorial, words that arein italics shouldnotbetaken as literal text, butrather as ageneric
description.Thestopstatementisoptionalandmayseemsuperfluoussincetheprogramwillstopwhen
itreachestheendanywaybutitisrecommendedtoalwaysterminateaprogramwiththe stopstatement
toemphasizethattheexecutionflowstopsthere.

Columnpositionrules
Fortran77isnotafreeformatlanguage,buthasaverystrictsetofrulesforhowthesourcecodeshould
beformatted.Themostimportantrulesarethecolumnpositionrules:

Col.1:Blank,ora"c"or"*"forcomments
Col.25:Statementlabel(optional)
Col.6:Continuationofpreviousline(optional)
Col.772:Statements
Col.7380:Sequencenumber(optional,rarelyusedtoday)
MostlinesinaFortran77programstartswith6blanksandendsbeforecolumn72,i.e.onlythe
statementfieldisused.NotethatFortran90allowsfreeformat.

Comments
Alinethatbeginswiththeletter"c"oranasteriskinthefirstcolumnisacomment.Commentsmay
appearanywhereintheprogram.Wellwrittencommentsarecrucialtoprogramreadability.Commercial
Fortrancodesoftencontainabout50%comments.YoumayalsoencounterFortranprogramsthatuse
theexclamationmark(!)forcomments.ThisishighlynonstandardinFortran77,butisallowedin
Fortran90.Theexclamationmarkmayappearanywhereonaline(exceptinpositions26).

Continuation
Occasionally,astatementdoesnotfitintoonesingleline.Onecanthenbreakthestatementintotwoor
morelines,andusethecontinuationmarkinposition6.Example:

c23456789(Thisdemonstratescolumnposition!)
cThenextstatementgoesovertwophysicallines
area=3.14159265358979
+*r*r
Anycharactercanbeusedinsteadoftheplussignasacontinuationcharacter.Itisconsideredgood
programmingstyletouseeithertheplussign,anampersand,ornumbers(2forthesecondline,3forthe
third,andsoon).

Blankspaces
BlankspacesareignoredinFortran77.SoifyouremoveallblanksinaFortran77program,the
programisstillsyntacticallycorrectbutalmostunreadableforhumans.

3.Variables,types,anddeclarations
Variablenames
VariablenamesinFortranconsistof16characterschosenfromthelettersazandthedigits09.The
firstcharactermustbealetter.(Note:Fortran90allowsvariablenamesofarbitrarylength).Fortran77
doesnotdistinguishbetweenupperandlowercase,infact,itassumesallinputisuppercase.However,
nearlyallFortran77compilerswillacceptlowercase.IfyoushouldeverencounteraFortran77
compilerthatinsistsonuppercaseitisusuallyeasytoconvertthesourcecodetoalluppercase.

Typesanddeclarations
Everyvariableshouldbedefinedinadeclaration.Thisestablishesthetypeofthevariable.Themost
commondeclarationsare:

integerlistofvariables
reallistofvariables
doubleprecisionlistofvariables
complexlistofvariables
logicallistofvariables
characterlistofvariables
Thelistofvariablesshouldconsistofvariablenamesseparatedbycommas.Eachvariableshouldbe
declaredexactlyonce.Ifavariableisundeclared,Fortran77usesasetofimplicitrulestoestablishthe
type.Thismeansallvariablesstartingwiththelettersinareintegersandallothersarereal.Manyold
Fortran77programsusestheseimplicitrules,butyoushouldnot!Theprobabilityoferrorsinyour
programgrowsdramaticallyifyoudonotconsistentlydeclareyourvariables.

Integersandfloatingpointvariables
Fortran77has only onetype forinteger variables. Integers are usually storedas 32bits (4bytes)
variables. Therefore, all integer variables should take on values in the range [m,m] where m is
approximately2*10^9.

Fortran77hastwodifferenttypesforfloatingpointvariables,called real and doubleprecision.


While real is often adequate, some numerical calculations need very high precision and double
precisionshouldbeused.Usuallyarealisa4bytevariableandthedoubleprecisionis8bytes,but
thisismachinedependent.SomenonstandardFortranversionsusethesyntax real*8todenote8byte
floatingpointvariables.

Theparameterstatement
Someconstantsappearmanytimesinaprogram.Itisthenoftendesirabletodefinethemonlyonce,in
thebeginningoftheprogram.Thisiswhatthe parameterstatementisfor.Italsomakesprogramsmore
readable.Forexample,thecircleareaprogramshouldhavebeenwrittenlikethis:

programcircle
realr,area,pi
parameter(pi=3.14159)
cThisprogramreadsarealnumberrandprints
ctheareaofacirclewithradiusr.
write(*,*)'Giveradiusr:'
read(*,*)r
area=pi*r*r
write(*,*)'Area=',area
stop
end
Thesyntaxoftheparameterstatementis
parameter(name=constant,...,name=constant)
Therulesfortheparameterstatementare:

The"variable"definedintheparameterstatementisnotavariablebutratheraconstantwhose
valuecanneverchange

A"variable"canappearinatmostoneparameterstatement

Theparameterstatement(s)mustcomebeforethefirstexecutablestatement

Somegoodreasonstousetheparameterstatementare:

ithelpsreducethenumberoftypos

itiseasytochangeaconstantthatappearsmanytimesinaprogram

4.Expressionsandassignment
Constants
Thesimplestformofanexpressionisaconstant.Thereare6typesofconstants,correspondingtothe6
datatypes.Herearesomeintegerconstants:
1
0
100
32767
+15
Thenwehaverealconstants:
1.0
0.25
2.0E6
3.333E1
TheEnotationmeansthatyoushouldmultiplytheconstantby10raisedtothepowerfollowingthe"E".
Hence,2.0E6istwomillion,while3.333E1isapproximatelyonethird.

Forconstantsthatarelargerthanthelargestrealallowed,orthatrequireshighprecision,double
precisionshouldbeused.Thenotationisthesameasforrealconstantsexceptthe"E"isreplacedbya
"D".Examples:
2.0D1
1D99
Here2.0D1isadoubleprecisiononefifth,while1D99isaonefollowedby99zeros.

Thenexttypeiscomplexconstants.Thisisdesignatedbyapairofconstants(integerorreal),separated
byacommaandenclosedinparentheses.Examplesare:
(2,3)
(1.,9.9E1)
Thefirstnumberdenotestherealpartandthesecondtheimaginarypart.

Thefifthtypeislogicalconstants.Thesecanonlyhaveoneoftwovalues:
.TRUE.
.FALSE.
Notethatthedotsenclosingthelettersarerequired.

Thelasttypeischaracterconstants.Thesearemostoftenusedasanarrayofcharacters,calledastring.
Theseconsistofanarbitrarysequenceofcharactersenclosedinapostrophes(singlequotes):
'ABC'
'Anythinggoes!'
'Itisaniceday'
Stringsandcharacterconstantsarecasesensitive.Aproblemarisesifyouwanttohaveanapostrophein
thestringitself.Inthiscase,youshoulddoubletheapostrophe:
'It''saniceday'

Expressions
Thesimplestexpressionsareoftheform
operandoperatoroperand
andanexampleis
x+y
Theresultofanexpressionisitselfanoperand,hencewecannestexpressionstogetherlike
x+2*y
Thisraisesthequestionofprecedence:Doesthelastexpressionmeanx+(2*y)or(x+2)*y?The
precedenceofarithmeticoperatorsinFortran77are(fromhighesttolowest):
**{exponentiation}
*,/{multiplication,division}
+,{addition,subtraction}
Alltheseoperatorsarecalculatedlefttoright,excepttheexponentiationoperator**,whichhasrightto
leftprecedence.Ifyouwanttochangethedefaultevaluationorder,youcanuseparentheses.
Theaboveoperatorsareallbinaryoperators.thereisalsotheunaryoperatorfornegation,whichtakes
precedenceovertheothers.Henceanexpressionlikex+ymeanswhatyouwouldexpect.

Extremecautionmustbetakenwhenusingthedivisionoperator,whichhasaquitedifferentmeaning
forintegersandreals.Iftheoperandsarebothintegers,anintegerdivisionisperformed,otherwiseareal
arithmeticdivisionisperformed.Forexample,3/2equals1,while3./2.equals1.5.

Assignment
Theassignmenthastheform
variable_name=expression
Theinterpretationisasfollows:Evaluatetherighthandsideandassigntheresultingvaluetothe
variableontheleft.Theexpressionontherightmaycontainothervariables,buttheseneverchange
value!Forexample,
area=pi*r**2
doesnotchangethevalueofpiorr,onlyarea.

Typeconversion
Whendifferentdatatypesoccurinthesameexpression,typeconversionhastotakeplace,either
explicitlyorimplicitly.Fortranwilldosometypeconversionimplicitly.Forexample,
realx
x=x+1
willconverttheintegeronetotherealnumberone,andhasthedesiredeffectofincrementingxbyone.
However,inmorecomplicatedexpressions,itisgoodprogrammingpracticetoforcethenecessarytype
conversionsexplicitly.Fornumbers,thefollowingfunctionsareavailable:
int
real
dble
ichar
char
Thefirstthreehavetheobviousmeaning.ichartakesacharacterandconvertsittoaninteger,while
chardoesexactlytheopposite.

Example:Howtomultiplytworealvariablesxandyusingdoubleprecisionandstoretheresultinthe
doubleprecisionvariablew:
w=dble(x)*dble(y)
Notethatthisisdifferentfrom
w=dble(x*y)

5.Logicalexpressions
Logicalexpressionscanonlyhavethevalue.TRUE.or.FALSE..Alogicalexpressioncanbeformedby
comparingarithmeticexpressionsusingthefollowingrelationaloperators:
.LT.meanslessthan(<)
.LE.lessthanorequal(<=)
.GT.greaterthan(>)
.GE.greaterthanorequal(>=)
.EQ.equal(=)
.NE.notequal(/=)
Soyoucannotusesymbolslike<or=forcomparisonsinFortran77.
Forexample:(x.eq.y)isvalidwhile(x=y)isnotvalidinFortran77.
Logicalexpressionscanbecombinedbythelogicaloperators.AND..OR..NOT.whichhavethe
obviousmeaning.

Logicalvariablesandassignment
Truthvaluescanbestoredinlogicalvariables.Theassignmentisanalogoustothearithmetic
assignment.Example:
logicala,b
a=.TRUE.
b=a.AND.3.LT.5/2
Theorderofprecedenceisimportant,asthelastexampleshows.Theruleisthatarithmeticexpressions
areevaluatedfirst,thenrelationaloperators,andfinallylogicaloperators.Hencebwillbeassigned
.FALSE.intheexampleabove.

LogicalvariablesareseldomusedinFortran.Butlogicalexpressionsarefrequentlyusedinconditional
statementsliketheifstatement.

6.Theifstatements
Animportantpartofanyprogramminglanguagearetheconditionalstatements.Themostcommonsuch
statementinFortranistheifstatement,whichactuallyhasseveralforms.Thesimplestoneisthelogical
ifstatement:
if(logicalexpression)executablestatement
Thishastobewrittenononeline.Thisexamplefindstheabsolutevalueofx:
if(x.LT.0)x=x
Ifmorethanonestatementshouldbeexecutedinsidetheif,thenthefollowingsyntaxshouldbeused:
if(logicalexpression)then
statements
endif
Themostgeneralformoftheifstatementhasthefollowingform:
if(logicalexpression)then
statements
elseif(logicalexpression)then
statements
:
:
else
statements
endif
Theexecutionflowisfromtoptobottom.Theconditionalexpressionsareevaluatedinsequenceuntil
oneisfoundtobetrue.Thentheassociatedcodeisexecutedandthecontroljumpstothenextstatement
aftertheendif.
Nestedifstatements
ifstatementscanbenestedinseverallevels.Toensurereadability,itisimportanttouseproper
indentation.Hereisanexample:
if(x.GT.0)then
if(x.GE.y)then
write(*,*)'xispositiveandx=y'
else
write(*,*)'xispositivebutx<y'
endif
elseif(x.LT.0)then
write(*,*)'xisnegative'
else
write(*,*)'xiszero'
endif
Youshouldavoidnestingmanylevelsofifstatementssincethingsgethardtofollow.

7.Loops
Forrepeatedexecutionofsimilarthings, loops areused.Ifyouarefamiliarwithotherprogramming
languagesyouhaveprobablyheardabout forloops, whileloops,and untilloops.Fortran77hasonly
oneloopconstruct,calledthedoloop.Thedoloopcorrespondstowhatisknownasaforloopinother
languages.Otherloopconstructshavetobesimulatedusingtheifandgotostatements.

doloops
Thedoloopisusedforsimplecounting.Hereisasimpleexamplethatprintsthecumulativesumsofthe
integersfrom1throughn(assumenhasbeenassignedavalueelsewhere):
integeri,n,sum
sum=0
do10i=1,n
sum=sum+i
write(*,*)'i=',i
write(*,*)'sum=',sum
10continue
Thenumber10isastatementlabel.Typically,therewillbemanyloopsandotherstatementsinasingle
programthatrequireastatementlabel.Theprogrammerisresponsibleforassigningauniquenumberto
eachlabelineachprogram(orsubprogram).Recallthatcolumnpositions25arereservedforstatement
labels.Thenumericalvalueofstatementlabelshavenosignificance,soanyintegernumberscanbe
used.Typically,mostprogrammersincrementlabelsby10atatime.

Thevariabledefinedinthedostatementisincrementedby1bydefault.However,youcandefineany
other integer to be the step. This program segment prints the even numbers between 1 and 10 in
decreasingorder:
integeri

do20i=10,1,2
write(*,*)'i=',i
20continue
Thegeneralformofthedoloopisasfollows:
dolabelvar=expr1,expr2,expr3
statements
labelcontinue
varistheloopvariable(oftencalledtheloopindex)whichmustbeinteger.expr1specifiestheinitial
valueofvar,expr2istheterminatingbound,andexpr3istheincrement(step).

Note:Thedoloopvariablemustneverbechangedbyotherstatementswithintheloop!Thiswillcause
greatconfusion.

ManyFortran77compilersallowdoloopstobeclosedbytheenddostatement.Theadvantageofthisis
thatthestatementlabelcanthenbeomittedsinceitisassumedthatan enddoclosesthenearestprevious
dostatement.Theenddoconstructiswidelyused,butitisnotapartofANSIFortran77.

whileloops
Themostintuitivewaytowriteawhileloopis

while(logicalexpr)do
statements
enddo
oralternatively,

dowhile(logicalexpr)
statements
enddo
Thestatementsinthebodywillberepeatedaslongastheconditioninthe whilestatementistrue.Even
thoughthissyntaxisacceptedbymanycompilers,itisnotANSIFortran77.Thecorrectwayistouse
ifandgoto:

labelif(logicalexpr)then
statements
gotolabel
endif
Hereisanexamplethatcalculatesandprintsallthepowersoftwothatarelessthanorequalto100:
integern

n=1
10if(n.le.100)then
n=2*n
write(*,*)n
goto10
endif

untilloops
Iftheterminationcriterionisattheendinsteadofthebeginning,itisoftencalledanuntilloop.The
pseudocodelookslikethis:
do
statements
until(logicalexpr)
Again,thisshouldbeimplementedinFortran77byusingifandgoto:
labelcontinue
statements
if(logicalexpr)gotolabel
Notethatthelogicalexpressioninthelatterversionshouldbethenegationoftheexpressiongiveninthe
pseudocode!

8.Arrays
Manyscientificcomputationsusevectorsandmatrices.ThedatatypeFortranusesforrepresentingsuch
objectsisthe array.Aonedimensionalarraycorrespondstoavector,whileatwodimensionalarray
correspondstoamatrix.TofullyunderstandhowthisworksinFortran77,youwillhavetoknownot
onlythesyntaxforusage,butalsohowtheseobjectsarestoredinmemoryinFortran77.

Onedimensionalarrays
Thesimplestarrayistheonedimensionalarray,whichisjustalinearsequenceofelementsstored
consecutivelyinmemory.Forexample,thedeclaration
reala(20)
declaresaasarealarrayoflength20.Thatis,aconsistsof20realnumbersstoredcontiguouslyin
memory.Byconvention,Fortranarraysareindexedfrom1andup.Thusthefirstnumberinthearrayis
denotedbya(1)andthelastbya(20).However,youmaydefineanarbitraryindexrangeforyour
arraysusingthefollowingsyntax:
realb(0:19),weird(162:237)
Here,bisexactlysimilartoafromthepreviousexample,excepttheindexrunsfrom0through19.
weirdisanarrayoflength237(162)+1=400.

Thetypeofanarrayelementcanbeanyofthebasicdatatypes.Examples:
integeri(10)
logicalaa(0:1)
doubleprecisionx(100)
Eachelementofanarraycanbethoughtofasaseparatevariable.Youreferencethei'thelementofarray
abya(i).Hereisacodesegmentthatstoresthe10firstsquarenumbersinthearraysq:
integeri,sq(10)

do100i=1,10
sq(i)=i**2
100continue
AcommonbuginFortranisthattheprogramtriestoaccessarrayelementsthatareoutofboundsor
undefined.Thisistheresponsibilityoftheprogrammer,andtheFortrancompilerwillnotdetectany
suchbugs!

Twodimensionalarrays
Matricesareveryimportantinlinearalgebra.Matricesareusuallyrepresentedbytwodimensional
arrays.Forexample,thedeclaration
realA(3,5)
definesatwodimensionalarrayof3*5=15realnumbers.Itisusefultothinkofthefirstindexasthe
rowindex,andthesecondasthecolumnindex.Hencewegetthegraphicalpicture:
(1,1)(1,2)(1,3)(1,4)(1,5)
(2,1)(2,2)(2,3)(2,4)(2,5)
(3,1)(3,2)(3,3)(3,4)(3,5)
Twodimensionalarraysmayalsohaveindicesinanarbitrarydefinedrange.Thegeneralsyntaxfor
declarationsis:
name(low_index1:hi_index1,low_index2:hi_index2)
Thetotalsizeofthearrayisthen
size=(hi_index1low_index1+1)*(hi_index2low_index2+1)
ItisquitecommoninFortrantodeclarearraysthatarelargerthanthematrixwewanttostore.(Thisis
becauseFortrandoesnothavedynamicstorageallocation.)Thisisperfectlylegal.Example:
realA(3,5)
integeri,j
c
cWewillonlyusetheupper3by3partofthisarray.
c
do20j=1,3
do10i=1,3
a(i,j)=real(i)/real(j)
10continue
20continue
TheelementsinthesubmatrixA(1:3,4:5)areundefined.Donotassumetheseelementsareinitializedto
zerobythecompiler(somecompilerswilldothis,butnotall).

Storageformatfor2dimensionalarrays
Fortranstoreshigherdimensionalarraysasacontiguouslinearsequenceofelements.Itisimportantto
knowthat2dimensionalarraysarestoredbycolumn.Sointheaboveexample,arrayelement(1,2)will
followelement(3,1).Thenfollowstherestofthesecondcolumn,thereafterthethirdcolumn,andsoon.

Consideragaintheexamplewhereweonlyusetheupper3by3submatrixofthe3by5array A(3,5).
The9interestingelementswillthenbestoredinthefirstninememorylocations,whilethelastsixare
notused.Thisworksoutneatlybecausethe leadingdimensionisthesameforboththearrayandthe
matrixwestoreinthearray.However,frequentlytheleadingdimensionofthearraywillbelargerthan
thefirstdimensionofthematrix.Thenthematrixwillnotbestoredcontiguouslyinmemory,evenifthe
arrayiscontiguous.Forexample,supposethedeclarationwasA(5,3)instead.Thentherewouldbetwo
"unused"memorycellsbetweentheendofonecolumnandthebeginningofthenextcolumn(againwe
areassumingthematrixis3by3).

Thismayseemcomplicated,butactuallyitisquitesimplewhenyougetusedtoit.Ifyouareindoubt,it
canbeusefultolookathowtheaddressofanarrayelementiscomputed.Eacharraywillhavesome
memoryaddressassignedtothebeginningofthearray,thatiselement(1,1).Theaddressofelement(i,j)
isthengivenby
addr[A(i,j)]=addr[A(1,1)]+(j1)*lda+(i1)
where lda istheleading(i.e.column)dimensionof A.Notethat lda isingeneraldifferentfromthe
actualmatrixdimension.ManyFortranerrorsarecausedbythis,soitisveryimportantyouunderstand
thedistinction!
Multidimensionalarrays
Fortran77allowsarraysofuptosevendimensions.Thesyntaxandstorageformatareanalogoustothe
twodimensionalcase,sowewillnotspendtimeonthis.

Thedimensionstatement
ThereisanalternatewaytodeclarearraysinFortran77.Thestatements
realA,x
dimensionx(50)
dimensionA(10,20)
areequivalentto
realA(10,20),x(50)
Thisdimensionstatementisconsideredoldfashionedstyletoday.

9.Subprograms
Whenaprogramsismorethanafewhundredlineslong,itgetshardtofollow.Fortrancodesthatsolve
realengineeringproblemsoftenhavetensofthousandsoflines.Theonlywaytohandlesuchbigcodes,
istouseamodularapproachandsplittheprogramintomanyseparatesmallerunitscalledsubprograms.

Asubprogramisa(small)pieceofcodethatsolvesawelldefinedsubproblem.Inalargeprogram,one
oftenhastosolvethesamesubproblemswithmanydifferentdata.Insteadofreplicatingcode,these
tasks should be solved by subprograms . The same subprogram can be invoked many times with
differentinputdata.

Fortranhastwodifferenttypesofsubprograms,calledfunctionsandsubroutines.

Functions
Fortranfunctionsarequitesimilartomathematicalfunctions:Theybothtakeasetofinputarguments
(parameters)andreturnavalueofsometype.Intheprecedingdiscussionwetalkedaboutuserdefined
subprograms.Fortran77alsohassomebuiltinfunctions.

Asimpleexampleillustrateshowtouseafunction:

x=cos(pi/3.0)
Herecosisthecosinefunction,soxwillbeassignedthevalue0.5(if pihasbeencorrectlydefined;
Fortran77hasnobuiltinconstants).TherearemanybuiltinfunctionsinFortran77.Someofthemost
commonare:
absabsolutevalue
minminimumvalue
maxmaximumvalue
sqrtsquareroot
sinsine
coscosine
tantangent
atanarctangent
expexponential(natural)
loglogarithm(natural)
Ingeneral,afunctionalwayshasatype.Mostofthebuiltinfunctionsmentionedabove,however,are
generic.Sointheexampleabove,piandxcouldbeeitheroftyperealordoubleprecision.The
compiler would check the types and use the correct version of cos (real or double precision).
Unfortunately,Fortranisnotreallya polymorphic languagesoingeneralyouhavetobecarefulto
matchthetypesofyourvariablesandyourfunctions!

Nowweturntotheuserwrittenfunctions.Considerthefollowingproblem:Ameteorologisthasstudied
theprecipitationlevelsintheBayAreaandhascomeupwithamodelr(m,t)whereristheamountof
rain,misthemonth,andtisascalarparameterthatdependsonthelocation.Giventheformulaforrand
thevalueoft,computetheannualrainfall.

Theobviouswaytosolvetheproblemistowritealoopthatrunsoverallthemonthsandsumsupthe
valuesofr.Sincecomputingthevalueofrisanindependentsubproblem,itisconvenienttoimplement
itasafunction.Thefollowingmainprogramcanbeused:
programrain
realr,t,sum
integerm

read(*,*)t
sum=0.0
do10m=1,12
sum=sum+r(m,t)
10continue
write(*,*)'Annualrainfallis',sum,'inches'

stop
end
Inaddition,thefunctionrhastobedefinedasaFortranfunction.Theformulathemeteorologistcame
upwithwas
r(m,t)=t/10*(m**2+14*m+46)ifthisispositive
r(m,t)=0otherwise
ThecorrespondingFortranfunctionis
realfunctionr(m,t)
integerm
realt
r=0.1*t*(m**2+14*m+46)
if(r.LT.0)r=0.0
return
end
Weseethatthestructureofafunctioncloselyresemblesthatofthemainprogram.Themaindifferences
are:
i) Functionshaveatype.Thistypemustalsobedeclaredinthecallingprogram.
ii)Thereturnvalueshouldbestoredinavariablewiththesamenameasthefunction.
iii)Functionsareterminatedbythereturnstatementinsteadofstop.
Tosumup,thegeneralsyntaxofaFortran77functionis:
typefunctionname(listofvariables)
declarations
statements
return
end
Thefunctionhastobedeclaredwiththecorrecttypeinthecallingprogramunit.Thefunctionisthen
calledbysimplyusingthefunctionnameandlistingtheparametersinparenthesis.
Subroutines
AFortranfunctioncanessentiallyonlyreturnonevalue.Oftenwewanttoreturntwoormorevalues(or
sometimesnone!).Forthispurposeweusethesubroutineconstruct.Thesyntaxisasfollows:
subroutinename(listofarguments)
declarations
statements
return
end
Notethatsubroutineshavenotypeandconsequentlyshouldnot(cannot)bedeclaredinthecalling
programunit.

Wegiveanexampleofaverysimplesubroutine.Thepurposeofthesubroutineistoswaptwointegers.
subroutineiswap(a,b)
integera,b
cLocalvariables
integertmp

tmp=a
a=b
b=tmp

return
end
Note that there are two blocks of variable declarations here. First, we declare the input/output
parameters,i.e.thevariablesthatarecommontoboththecallerandthecallee.Afterwards,wedeclare
thelocalvariables,i.e.thevariablesthatcanonlybeusedwithinthissubprogram.Wecanusethesame
variablenamesindifferentsubprogramsandthecompilerwillknowthattheyaredifferentvariablesthat
justhappentohavethesamenames.

Callbyreference
Fortran77usesthesocalled callbyreference paradigm.Thismeansthatinsteadofjustpassingthe
values of the function/subroutine arguments (callbyvalue), the memory address of the arguments
(pointers)arepassedinstead.Asmallexampleshouldshowthedifference:
programcallex
integerm,n
c
m=1
n=2
calliswap(m,n)
write(*,*)m,n
stop
end
Theoutputfromthisprogramis"21",justasonewouldexpect.However,ifFortran77hadbeenusing
callbyvaluethentheoutputwouldhavebeen"12",i.e.thevariablesmandnwereunchanged!The
reasonforthisisthatonlythevaluesofmandnhadbeencopiedtothesubroutineiswap,andevenifa
andbwereswappedinsidethesubroutinethenewvalueswouldnothavebeenpassedbacktothemain
program.

Intheaboveexample,callbyreferencewasexactlywhatwewanted.Butyouhavetobecarefulabout
thiswhenwritingFortrancode,becauseitiseasytointroduceundesired sideeffects.Forexample,
sometimesitistemptingtouseaninputparameterinasubprogramasalocalvariableandchangeits
value.Youshould never dothissincethenewvaluewillthenpropagatebacktothecallingprogram
withanunexpectedvalue!

10.RandomnumbersandMonteCarlosimulations
Allcomputersimulations(e.g.rollingthedice,tossingacoin)makeuseofafunctionthatgivesa
randomnumberuniformlybetween[0,1),i.e.includes0,butnot1.InFortranthisfunctionis
ran(seed),whereseedisanintegervariableusedtogenerate(seed)thesequenceofrandomnumbers.
Belowisasampleprogramthatwillgenerate10randomnumbersintheinterval[0,1).
programrandom
integerseed,n
seed=7654321
cseedshouldbesettoalargeoddintegeraccordingtotheFortranmanual
n=10
don=1,10
r=ran(seed)
write(6,*)n,r
ccouldusea*insteadof6inthewritestatement
enddo
stop
end
Theseedisusedtogeneratetherandomnumbers.Iftwoprograms(orthesameprogramruntwice)use
thesameseed,thentheywillgetthesamesequenceofrandomnumbers.Tryrunningtheaboveprogram
twice!Ifyouwantadifferentsequenceofrandomnumberseverytimeyourunyourprogramthenyou
mustchangeyourseed.Onewaytohaveyourprogramchangetheseedforyouistouseafunctionthat
givesanumberthatdependsonthetimeofday.Forexampleusingthefunction secnds(x)givesthe
numberofseconds(minusx)sincemidnight.So,aslongasyoudontrerunyourprogramtooquickly,
orrunitexactlythesametimeontwodifferentdays,thisFortranprogramwillgiveadifferentsetof
randomnumberseverytimeitisrun.
programrandom
integerseed,seed1,n
realx
seed1=7654321
x=0.0
cseedshouldbesettoalargeoddintegeraccordingtothemanual
csecnds(x)givesnumberofsecondsxelapsedsincemidnight
cthe2*int(secnds(x))isalwayseven(int=givesinteger)soseedisalwaysodd
seed=seed1+2*int(secnds(x))
n=10
don=1,10
r=ran(seed)
write(6,*)n,r
ccouldusea*insteadof6inthewritestatement
enddo
stop
end
Therandomnumbergeneratorfunctiononlygivesnumbersintheinterval[0,1).Sometimeswewant
randomnumbersinadifferentinterval,e.g.[1,1).Asimpletransformation canbeusedtochange
intervals.Forexample,ifwewantarandomnumber(x)intheinterval[a,b)wecandosousing:
x=(ba)*ran(seed)a
Thusfortheinterval[1,1)weget:x=2*ran(seed)1.
Infact,wecantakeoursetofnumbersfromtheran(seed)functionwhichhaveauniformprobability
distributionintheinterval[0,1)andturnthemintoasetofnumbersthatlookliketheycomefromjust
aboutanyprobabilitydistributionwithanyintervalthatonecanimagine!
Afewexamples:
dice=int(1+6*ran(seed))Thisgeneratestherollofa6sideddie.

g=sqrt(2*log(ran(seed)))*cos(2*pi*ran(seed))
This generates a random number from a gaussian distribution with mean=0 and
variance=1.Weassumethatpiisalreadyinitializedto3.14159intheprogram.

t= a*log(ran(seed)) This generates a random number from an exponential


distributionwithlifetime=a.

Beingabletotransformtherandomnumbersobtainedfromran(seed)intoanyprobabilitydistribution
functionwewantisextremelyusefulandformsthebasisofallcomputersimulations.

ThistypeofsimulationoftengoesbythenameMonteCarlo.WhyMonteCarlo?Intheprecomputer
eraapopularwaytoobtainasetofrandomnumberswastousearoulettewheel,justthetypefoundin
theMediterraneancityofMonteCarlo,famousforitsgamblingcasino.Thisallhappenedinthelate
1940s.Ifthistechniquehadbecomepopularinthelate1950swedprobablybecallingitLasVegas!

11.SimpleI/O
Animportantpartofanycomputerprogramistohandleinputandoutput.Inourexamplessofar,we
havealreadyusedthetwomostcommonFortranconstructsforthis: readandwrite.FortranI/Ocanbe
quitecomplicated,sowewillonlydescribesomesimplercasesinthistutorial.

Readandwrite
Readisusedforinput,whilewriteisusedforoutput.Asimpleformis
read(unitno,formatno)listofvariables
write(unitno,formatno)listofvariables
Theunitnumbercanrefertoeitherstandardinput,standardoutput,orafile.Thiswillbedescribedin
latersection.Theformatnumberreferstoalabelforaformatstatement,whichwillbedescribedshortly.

Itispossibletosimplifythesestatementsfurtherbyusingasterisks(*)forsomearguments,likewehave
doneinallourexamplessofar.Thisissometimescalledlistdirectedread/write.
read(*,*)listofvariables
write(*,*)listofvariables
Thefirststatementwillreadvaluesfromthestandardinputandassignthevaluestothevariablesinthe
variablelist,whilethesecondonewritestothestandardoutput.

Examples
HereisacodesegmentfromaFortranprogram:
integerm,n
realx,y
read(*,*)m,n
read(*,*)x,y
Wegivetheinputthroughstandardinput(possiblythroughadatafiledirectedtostandardinput).Adata
file consists of records according to traditional Fortran terminology. In our example, each record
containsanumber(eitherintegerorreal).Recordsareseparatedbyeitherblanksorcommas.Hencea
legalinputtotheprogramabovewouldbe:
1100
1.01e+2
Or,wecouldaddcommasasseparators:
1,100
1.0,1e+2
NotethatFortran77inputislinesensitive,soitisimportanttohavetherightnumberofinputelements
(records)oneachline.Forexample,ifwegavetheinputallononelineas
1,100,1.0,1e+2
thenmandnwouldbeassignedthevalues1and100respectively,butthelasttwovalueswouldbe
discarded,leavingxandyundefined.

12.Formatstatements
Sofarwehaveonlyshowedfreeformatinput/output.Thisusesasetofdefaultrulesforhowtooutput
valuesofdifferenttypes(integers,reals,characters,etc.).Oftentheprogrammerwantstospecifysome
particularinputoroutputformat,e.g.howmanydecimalsinrealnumbers.ForthispurposeFortran77
hastheformatstatement.Thesameformatstatementsareusedforbothinputandoutput.

Syntax

write(*,label)listofvariables
labelformatformatcode
Asimpleexampledemonstrateshowthisworks.Sayyouhaveanintegervariableyouwanttoprintina
field4characterswideandarealnumberyouwanttoprintinfixedpointnotationwith3decimalplaces.
write(*,900)i,x
900format(I4,F8.3)
The format label 900 is chosen somewhat arbitrarily, but it is common practice to number format
statementswithhighernumbersthanthecontrolflowlabels.Afterthekeyword format followsthe
formatcodesenclosedinparenthesis.ThecodeI4standsforanintegerwithwidthfour,whileF8.3
meansthatthenumbershouldbeprintedusingfixedpointnotationwithfieldwidth8and3decimal
places.

Theformatstatementmaybelocatedanywherewithintheprogramunit.Therearetwoprogramming
styles: Either the format statement follows directly after the read/write statement, orall the format
statementsaregroupedtogetherattheendofthe(sub)program.

Commonformatcodes
Themostcommonformatcodelettersare:
Atextstring
Ddoubleprecisionnumbers,exponentnotation
Erealnumbers,exponentnotation
Frealnumbers,fixedpointformat
Iinteger
Xhorizontalskip(space)
/verticalskip(newline)
TheformatcodeF(andsimilarly D,E)hasthegeneralformFw.d where w isaninteger constant
denotingthefieldwidthanddisanintegerconstantdenotingthenumberofsignificantdigits.

Forintegersonlythefieldwidthisspecified,sothesyntaxis Iw.Similarly,characterstringscanbe
specifiedasAwbutthefieldwidthisoftendropped.

Ifanumberorstringdoesnotfilluptheentirefieldwidth,spaceswillbeadded.Usuallythetextwillbe
adjustedtotheright,buttheexactrulesvaryamongthedifferentformatcodes.

Forhorizontalspacing,thenXcodeisoftenused.Thismeansnhorizontalspaces.Ifnisomitted,n=1is
assumed.Forverticalspacing(newlines),usethecode /.Eachslashcorrespondstoonenewline.Note
thateachreadorwritestatementbydefaultendswithanewline(hereFortrandiffersfromC).

Someexamples
ThispieceofFortrancode
x=0.025
write(*,100)'x=',x
100format(A,F)
write(*,110)'x=',x
110format(A,F5.3)
write(*,120)'x=',x
120format(A,E)
write(*,130)'x=',x
130format(A,E8.1)
producesthefollowingoutputwhenwerunit:
x=0.0250000
x=0.025
x=0.2500000E01
x=0.3E01
Notehowblanksareautomaticallypaddedontheleftandthatthedefaultfieldwidthforrealnumbersis
usually14.WeseethatFortran77followstheroundingrulethatdigits04areroundeddownwards
while59isroundedupwards.

Inthisexampleeachwritestatementusedadifferentformatstatement.Butitisperfectlyfinetousethe
sameformatstatementfrommanydifferentwritestatements.Infact,thisisoneofthemainadvantages
ofusingformatstatements.Thisfeatureishandywhenyouprinttablesforinstance,andwanteachrow
tohavethesameformat.

Formatstringsinread/writestatements
Insteadofspecifyingtheformatcodeinaseparateformatstatement,onecangivetheformatcodeinthe
read/writestatementdirectly.Forexample,thestatement

write(*,'(A,F8.3)')'Theanswerisx=',x
isequivalentto

write(*,990)'Theanswerisx=',x
990format(A,F8.3)
Sometimestextstringsaregivenintheformatstatements,e.g.thefollowingversionisalsoequivalent:
write(*,999)x
999format('Theanswerisx=',F8.3)

Implicitloopsandrepeatcounts
Nowletusdoamorecomplicatedexample.Sayyouhaveatwodimensionalarrayofintegersandwant
toprinttheupperleft5by10submatrixwith10valueseachon5rows.Hereishow:
do10i=1,5
write(*,1000)(a(i,j),j=1,10)
10continue
1000format(I6)
Wehaveanexplicitdoloopovertherowsandanimplicitloopoverthecolumnindexj.

Oftenaformatstatementinvolvesrepetition,forexample
950format(2X,I3,2X,I3,2X,I3,2X,I3)
Thereisashorthandnotationforthis:

950format(4(2X,I3))
Itisalsopossibletoallowrepetitionwithoutexplicitlystatinghowmanytimestheformatshouldbe
repeated.Supposeyouhaveavectorwhereyouwanttoprintthefirst50elements,withtenelementson
eachline.Hereisoneway:

write(*,1010)(x(i),i=1,50)
1010format(10I6)
Theformatstatementssaystennumbersshouldbeprinted.Butinthewritestatementwetrytoprint50
numbers.Soafterthetenfirstnumbershavebeenprinted,thesameformatstatementisautomatically
usedforthenexttennumbersandsoon.

13.FileI/O
Sofarwehaveassumedthattheinput/outputhasbeentothestandardinputorthestandardoutput.Itis
alsopossibletoreadorwritefromfileswhicharestoredonsomeexternalstoragedevice,typicallya
disk(harddisk,floppy)oratape.InFortraneachfileisassociatedwitha unitnumber,aninteger
between1and99.Someunitnumbersarereserved:5isstandardinput,6isstandardoutput.

Openingandclosingafile
Beforeyoucanuseafileyouhavetoopenit.Thecommandis

open(listofspecifiers)
wherethemostcommonspecifiersare:

[UNIT=]u
IOSTAT=ios
ERR=err
FILE=fname
STATUS=sta
ACCESS=acc
FORM=frm
RECL=rl
Theunitnumberuisanumberintherange999thatdenotesthisfile(theprogrammermaychoseany
numberbuthe/shehastomakesureitisunique).
iosistheI/Ostatusidentifierandshouldbeanintegervariable.Uponreturn,iosiszeroifthestement
wassuccessfulandreturnsanonzerovalueotherwise.

errisalabelwhichtheprogramwilljumptoifthereisanerror.
fnameisacharacterstringdenotingthefilename.

staisacharacterstringthathastobeeitherNEW,OLDorSCRATCH.Itshowsthepriorstatusofthe
file.Ascrathfileisafilethatiscreatedanddeletedwhenthefileisclosed(ortheprogramends).

accmustbeeitherSEQUENTIALorDIRECT.ThedefaultisSEQUENTIAL.

frmmustbeeitherFORMATTEDorUNFORMATTED.ThedefaultisUNFORMATTED.

rlspecifiesthelengthofeachrecordinadirectacccessfile.

Formoredetailsonthesespecifiers,seeagoodFortran77book.
Afterafilehasbeenopened,youcanaccessitbyreadandwritestatements.Whenyouaredonewiththe
file,itshouldbeclosedbythestatement

close([UNIT=]u[,IOSTAT=ios,ERR=err,STATUS=sta])
where,asusual,theparametersinbracketsareoptional.

Readandwriterevisited
Theonlynecessarychangefromourprevioussimplifiedread/writestatements,isthattheunitnumber
mustbespecified.Butfrequentlyonewantstoaddmorespecifiers.Hereishow:

read([UNIT=]u,[FMT=]fmt,IOSTAT=ios,ERR=err,END=s)
write([UNIT=]u,[FMT=]fmt,IOSTAT=ios,ERR=err,END=s)
wheremostofthespecifiershavebeendescribedabove.TheEND=sspecifierdefineswhichstatement
labeltheprogramjumpstoifitreachesendoffile.

Example
Youaregivenadatafilewithxyzcoordinatesforabunchofpoints.Thenumberofpointsisgivenon
thefirstline.Thefilenameofthedatafileispoints.dat.Theformatforeachcoordinateisknowntobe
F10.4.Hereisashortprogramthatreadsthedatainto3arraysx,y,z:

programinpdat
c
cThisprogramreadsnpointsfromadatafileandstoresthemin
c3arraysx,y,z.
c
integernmax,u
parameter(nmax=1000,u=20)
realx(nmax),y(nmax),z(nmax)
cOpenthedatafile
open(u,FILE='points.dat',STATUS='OLD')

cReadthenumberofpoints
read(u,*)n
if(n.GT.nmax)then
write(*,*)'Error:n=',n,'islargerthannmax=',nmax
goto9999
endif

cLoopoverthedatapoints
do10i=1,n
read(u,100)x(i),y(i),z(i)
10enddo
100format(3(F10.4))

cClosethefile
close(u)

cNowweshouldprocessthedatasomehow...
c(missingpart)

9999stop
end

14.Commonblocks
Fortran 77 has no global variables, i.e. variables that are shared among several program units
(subroutines).Theonlywaytopassinformationbetweensubroutineswehaveseensofar,istousethe
subroutineparameterlist.Sometimesthisisinconvenient,e.g.whenmanysubroutinessharealargeset
ofparameters.Insuchcasesonecanuseacommonblock.Thisisawaytospecifythatcertainvariables
should be shared among certain subroutines. But in general, the use of common blocks should be
minimized.

Example
Supposeyouhavetwoparametersalphaandbetathatmanyofyoursubroutinesneed.Thefollowing
exampleshowshowitcanbedoneusingcommonblocks.

programmain
somedeclarations
realalpha,beta
common/coeff/alpha,beta

statements
stop
end

subroutinesub1(somearguments)
declarationsofarguments
realalpha,beta
common/coeff/alpha,beta

statements
return
end

subroutinesub2(somearguments)
declarationsofarguments
realalpha,beta
common/coeff/alpha,beta

statements
return
end
Herewedefineacommonblockwiththename coeff.Thecontentofthecommonblockisthetwo
variables alpha and beta.Acommonblockcancontainasmanyvariablesasyoulike.Theydonot
needtoallhavethesametype.Everysubroutinethatwantstouseanyofthevariablesinthecommon
blockhastodeclarethewholeblock.

Notethatinthisexamplewecouldeasilyhaveavoidedcommonblocksbypassingalphaandbetaas
parameters(arguments).Agoodruleistotrytoavoidcommonblocksifpossible.However,therearea
fewrarecaseswherethereisnoothersolution.

Syntax

common/name/listofvariables
Youshouldknowthat
The common statement should appear together with the variable declarations, before the executable
statements.
Differentcommonblocksmusthavedifferentnames(justlikevariables).Avariablecanbelongtomore
thanonecommonblock.
Thevariablesinacommonblockdonotneedtohavethesamenameseachplacetheyoccur(althoughit
isagoodideatodoso),buttheymustbelistedinthesameorderandhavethesametype.
Toillustratethis,lookatthefollowingcontinuationofourexample:

subroutinesub3(somearguments)
declarationsofarguments
reala,b
common/coeff/a,b

statements
return
end
Thisdeclarationisequivalenttothepreviousversionthatused alphaandbeta.Itisrecommendedthat
youalwaysusethesamevariablenamesforthesamecommonblocktoavoidconfusion.Hereisa
dreadfulexample:

subroutinesub4(somearguments)
declarationsofarguments
realalpha,beta
common/coeff/beta,alpha

statements
return
end
Nowalphaisthebetafromthemainprogramandviceversa.Ifyouseesomethinglikethis,itis
probablyamistake.Suchbugsareveryhardtofind.
Arraysincommonblocks
Common blocks can include arrays,too.But again, this is not recommended. The major reasonis
flexibility.Anexampleshowswhythisissuchabadidea.Supposewehavethefollowingdeclarations
inthemainprogram:

programmain
integernmax
parameter(nmax=20)
integern
realA(nmax,nmax)
common/matrix/A,n,nmax
ThiscommonblockcontainsfirstalltheelementsofA,thentheintegersnandnmax.Nowassumeyou
wanttousethematrixAinsomesubroutines.Thenyouhavetoincludethesamedeclarationsinall
thesesubroutines,e.g.

subroutinesub1(...)
integernmax
parameter(nmax=20)
integern
realA(nmax,nmax)
common/matrix/A,n,nmax
Arrayswithvariabledimensionscannotappearincommonblocks,thusthevalueof nmax hastobe
exactlythesameasinthemainprogram.Recallthatthesizeofamatrixhastobeknownatcompile
time, hence nmax has to be defined in a parameter statement. It would be tempting to delete the
parameterstatementinthesubroutinesincenmaxbelongstothecommonblock,butthiswouldbe
illegal.

Thisexampleshowsthereisusuallynothingtogainbyputtingarraysincommonblocks.Hencethe
preferredmethodinFortran77istopassarraysasargumentstosubroutines(alongwiththeleading
dimensions).

15.dataandblockdata
Thedatastatement
Thedatastatementisanotherwaytoinputdatathatareknownatthetimewhentheprogramiswritten.
Itissimilartotheassignmentstatement.Thesyntaxis:

datalistofvariables/listofvalues/,...
wherethethreedotsmeansthatthispatterncanberepeated.Hereisanexample:

datam/10/,n/20/,x/2.5/,y/2.5/
Wecouldalsohavewrittenthis

datam,n/10,20/,x,y/2*2.5/
Wecouldhaveaccomplishedthesamethingbytheassignments

m=10
n=20
x=2.5
y=2.5
Thedatastatementismorecompactandthereforeoftenmoreconvenient.Noticeespeciallythe
shorthandnotationforassigningidenticalvaluesrepeatedly.

Thedatastatementisperformedonlyonce,rightbeforetheexecutionoftheprogramstarts.Forthis
reason,thedatastatementismainlyusedinthemainprogramandnotinsubroutines.

Thedatastatementcanalsobeusedtoinitializearrays(vectors,matrices).Thisexampleshowshowto
makesureamatrixisallzeroswhentheprogramstarts:
realA(10,20)
dataA/200*0.0/
Somecompilerswillautomaticallyinitializearrayslikethisbutnotall,soifyourelyonarrayelements
tobezeroitisagoodideatofollowthisexample.Ofcourseyoucaninitializearraystoothervalues
thanzero.Youmayeveninitializeindividualelements:
dataA(1,1)/12.5/,A(2,1)/33.3/,A(2,2)/1.0/
Oryoucanlistalltheelementsforsmallarrayslikethis:
integerv(5)
realB(2,2)
datav/10,20,30,40,50/,B/1.0,3.7,4.3,0.0/
Thevaluesfortwodimensionalarrayswillbeassignedincolumnfirstorderasusual.

Theblockdatastatement
The data statement cannot be used for variables contained in a common block. There is a special
"subroutine"forthispurpose,calledblockdata.Itisnotreallyasubroutine,butitlooksabitsimilar
becauseitisgivenasaseparateprogramunit.Hereisanexample:
blockdata
integernmax
parameter(nmax=20)
realv(nmax),alpha,beta
common/vector/v,alpha,beta
datav/20*100.0/,alpha/3.14/,beta/2.71/
end
Justasthedatastatement,blockdataisexecutedoncebeforetheexecutionofthemainprogramstarts.
Thepositionoftheblockdata"subroutine"inthesourcecodeisirrelevant(aslongasitisnotnested
insidethemainprogramorasubprogram).

16.Debugginghints
Ithasbeenestimatedthatabout90%ofthetimeittakestodevelopcommercialsoftwareisspent
debuggingandtesting.Thisshowshowimportantitistowritegoodcodeinthefirstplace.

Still,wealldiscoverbugsfromtimetotime.Herearesomehintsforhowtotrackthemdown.
Usefulcompileroptions
MostFortrancompilerswillhaveasetofoptionsyoucanturnonifyoulike.Thefollowingcompiler
optionsarespecifictotheSunFortran77compiler,butmostcompilerswillhavesimilaroptions
(althoughthelettersmaybedifferent).
ansiThiswillwarnyouaboutallnonstandardFortran77extensionsinyourprogram.

uThiswilloverridetheimplicittyperulesandmakeallvariablesundeclaredinitially.Ifyourcompiler
doesnothavesuchanoption,youcanachievealmostthesamethingbyaddingthedeclaration
implicitnone(az)inthebeginningofeach(sub)program.
CCheckforarraybounds.Thecompilerwilltrytodetectifyouaccessarrayelementsthatareout
ofbounds.Itcannotcatchallsucherrors,however.
Somecommonerrors
Herearesomecommonerrorstowatchoutfor:

Makesureyourlinesendatcolumn72.Therestwillbeignored!

Haveyoudoneintegerdivisionwhenyouwantedrealdivision?

Doyourparameterlistsinthecallingandthecalledprogrammatch?

Doyourcommonblocksmatch?

Debuggingtools
Ifyouhaveabug,youhavetotrytolocateit.Syntaxerrorsareeasytofind.Theproblemiswhenyou
haveruntimeerrors.Theoldfashionedwaytofinderrorsistoaddwritestatementsinyourcodeand
trytotrackthevaluesofyourvariables.Thisisabittedioussinceyouhavetorecompileyoursource
codeeverytimeyouchangetheprogramslightly.Todayonecanusespecial debuggers whichisa
convenienttool.Youcanstepthroughaprogramlinebylineordefineyourownbreakpoints,youcan
displaythevaluesofthevariablesyouwanttomonitor,andmuchmore.

17.RunningFortranonthePhysicsDepartmentsVAX
(OHSTPY)Computer
=>donottypethes,justwordsinsidethes!

1)LogintoOHSTPY.
2)Createyourprogrambytyping"editname.for"andtypeintheprogram.Here,nameiswhateveryou
wishtocallyourprogram.Forexample,test.fororlab1.for.Theextension.fortellsthecomputerthat
thisfilecontainsFortrancode.Theeditcommandrunsaprogramthatallowsyoutocreateandeditafile
(name.for)onthecomputersdisk.WhendoneenteringyourFortrancommands,hit <CTRL>zand
type"exit"tosavetherecenteditsandquitor"quit"toquitwithoutsavingtheedits.

3)Compiletheprogrambytyping"fortranname",wherenamecouldbe test ifyourfilewasnamed


test.for.ThecompilerisacomputerprogramthatreadsyourFortrancodeandtranslatesitintocodethat
thecomputeractuallyruns.Thecompilercreatesanewfilecalledname.obj(e.g.test.obj).Ifthereare
anysyntaxerrorsinyourFortrancodethecompilerwillflagthemandprintoutanerrormessage(s)to
thecomputerscreen.Youmustfixalloftheerrorsintheprogrambeforeyoucanruntheprogram.

4)LinkyourFortrancode(e.g.test.for)withotherprogramsnecessarytorunyourprogrambytyping
"linktest".Thiscreatesanewfile(anexecutable)calledname.exe(e.g.test.exe).Oncetheexecutable
fileiscreated,execute(run)theprogrambytyping"runname"(e.g.runtest).

5)Checkyouroutputcarefully!Justbecausetheprogramrunsdoesnotmeanitactuallyworks!
18.AsampleFortranprogramforLab1
C Thisprogramsimulatesrollingasixsideddice,eachsidehas1to6dots.
CThenumberoftimesthedieistossedisgivenbytheinteger
Cvariable:roll.
C
C Theresultofanindividualtoss(a1or
C2,..or6dots)isgivenbytheintegervariable:dice.
C
C TherealvariablecountisanARRAYwithsixentries.
C Countkeepstrackofthenumberoftimesa1(2,etc)wasrolled.
C Forexampleifarray(1)=5andarray(2)=7thenaonewas
C rolled5timesandatwowasfilled7times.
C
C FORTRANisbasedonlinesandcolumns,usuallyoneinstructionperline.
C InFORTRANcomputerinstructionsstartincolumn7.
C InFORTRANaCincolumn1flagsthislineasacomment.
C234567
C InFORTRANacharacterincolumn6flagsthisasacontinuationline.
Ctoassumethatitisacommentlineandignoreit.
C linesinREDaretheactualFortrancode.
implicitnone
characterkey
realcount(6),RAN
integeri,dice,roll,seed
C
CSpecialprecautioninintegerdivision:dividingoneinteger
Cbyanotherintegergivesanotherinteger,e.g.i=3,j=2,
Cthenc=i/j=1.0.Togetthecorrectanswer,defineiand
Cjasrealnumbers.
C
CRANisacomputerfunctionthatgivesusarandomnumberin
Ctherange[0,1).InitializetherandomnumbergeneratorRAN
Cwithalargeoddintegerseed.
C
seed=432211111
10 continue
C"10"isthestatementnumberofthecontinuecommand.
CStatementnumbersshouldstartatcolumn2orlaterandendatcolumn5.
CAllstatementnumbersmustbeauniqueinteger.
C
CInitializationofvariables
C Herewehaveadoloop,whichrepeatsitself6times
dodice=1,6
count(dice)=0
enddo
CWritetounit6(screen)andreadfromunit5(keyboard).
write(6,*)'Howmanyrollsofdice:'
read(5,*)roll
doi=1,roll
dice=INT(1+6*RAN(seed))
count(dice)=count(dice)+1
enddo
doi=1,6
write(6,*)i,count(i)
enddo
CThe">"characterat6thcharacterlocationindicates
Ccontinuationofaprogramline.
C
write(6,*)Hit<return>tocontinueortypeqorQ',
>'and<return>toquittheprogram.'
read(5,20)key
CDefinekeyasaonecharactervariable("a1").Ifyouuse
C*insteadof20,youdonotexplicitlyspecifytheformat.
20format(a1)
if(key.ne.'q'.and.key.ne.'Q')goto10
end

You might also like