Вы находитесь на странице: 1из 30

3/14/2015

IntroductiontoFortranProgramming

PROGRAMMINGINFORTRAN77
IfyoudonothaveaWORKERwindowbelow
***openonenowbyinvokingthe'WorkerWindow'***
optioninthe'Coursework'menu.

TableofContents
0.Introduction
1.FortranStatements
2.DataTypes,ConstantsandVariables
Types
Constants
Variables
Implicittyping
3.Operators
Assignment
Arithmetic
Typeconversion
Relational
Logical
Character
4.TaskRepetitionUsingDOLoops
TheDOstatement
TheDOWHILEstatement
5.ConditionalConstructs
ThesimpleIFstatement
TheblockIFstatement
6.Arrays
Multidimensionalarrays
7.Input/Output
TerminalI/O
Listdirectedoutput
Listdirectedinput
Formattedoutput
Formattedinput
FileI/O
Listdirectedoutput
Listdirectedinput
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

1/30

3/14/2015

IntroductiontoFortranProgramming

Formattedoutput
Formattedinput
8.TheUseofFormat
9.Subprograms
Intrinsicfunctions
Functionsubprograms
Subroutines
10.Common
Namedcommonblocks
Blankcommon

0.INTRODUCTION
YoushouldalreadyhavemetsomeofthefeaturesoftheFortran77programminglanguageinthe
IntroductoryCourse.IFYOUHAVENOTCOMPLETEDTHEPROGRAMMINGTUTORIALIN
THEINTRODUCTORYCOURSE,YOUARESTRONGLYADVISEDNOTTOPROCEEDWITH
THISTUTORIAL,BUTTOGOBACKANDDOIT!
TheFortranlanguageisstillevolvingFortran77isaninternationallyagreedstandardtowhichnearly
allcurrentcompilersconform,butthereisnowarevisedstandard,Fortran90,whichhasbeenagreed
butwhichhasnotyetbeenwidelyimplemented.However,manycompilers,includingthatavailable
onthismachine,alreadyincorporatesomeofthenewfeaturesoftheFortran90standardasextensions
toFortran77.Wewillintroducesomeofthesenewfeaturesinthistutorialbutwillalwayspointout
thattheyarenotpartoftheFortran77standard,butareextensionsthereofbylabellingthemF90.
However,YOUARESTRONGLYENCOURAGEDTOUSETHEF90FEATURES.
Wewillbeginbyremindingyouofthestructureoftheprojectileprogramthatfeaturedinthe
IntroductoryCoursebutwewillnowtrytobealittlemoresystematicinourdescription!Getholdof
acopyoftheprogrambygoingtotheWORKERwindow,clickingthemouseandtyping
cp/usr/local/text/cplabwork/examples/fortprogs/proj1.fproj1.f

or
cp$TFILES/cplabwork/examples/fortprogs/proj1.fproj1.f

Theninvoketheemacseditoronyourcopyofthefilebytyping
ueproj1.f

ClickhereifyouwishtoreturntotheTableofContents.

1.FORTRANPROGRAMSTATEMENTS
Fortran77programsaretypedinlinesofupto72characters,withthefirstsixcolumnsofeachline
reservedforspecialpurposes.Asaresult,Fortran77statementsALWAYSBEGINAT,ORAFTER,
COLUMN7.
Oneofthespecialpurposesforwhichthefirstsixcolumnsmaybeusedisshownintheprojectile
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

2/30

3/14/2015

IntroductiontoFortranProgramming

program:ifthefirstcolumncontainsa'c'ora'*'thenthewholelineistreatedasaCOMMENTandis
ignoredwhentheprogramiscompiledintoexecutablecode.
AsecondspecialuseofthefirstsixcolumnsistospecifyaCONTINUATIONLINE.Ifcolumn6ofa
linecontainsanycharacterotherthanaspaceorazerothenthelineistreatedasacontinuationofthe
previousline.Inthiscasecolumns15ofthecontinuationlineMUSTBEBLANK,andcolumn7is
treatedasifitcameimmediatelyaftercolumn72ofthepreviousline!
Thethirdspecialuseofthefirstsixcolumns(actually,thefirstfivecolumns)isforidentifyinga
statementbymeansofaSTATEMENTLABEL,whichisaninteger,writtenincolumns15.The
numberchosencanbeanyintegerintherange199999aslongasitisuniquetothestatementbeing
labelled.Wewillencounterusesofstatementlabelslaterinthetutorialfornow,notethattheyarenot
generallyrequiredandtheiruseisDISCOURAGED.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!F90FEATURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

ThestrictFortran77standardrequirestheuseofuppercaselettersonlyinprogramstatements,except
incommentstatementsorwhenwritingstringsoftexttobeusedinprintedoutput.Fortran90allows
theuseoflowercaseaswellasuppercaseletters.Note,however,thatupperandlowercaseare
EQUIVALENTtheyaredistinguishedonlywhentheyformpartofcharactersequences,NOTwhen
usedinnamesofvariablesorconstants.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

ClickhereifyouwishtoreturntotheTableofContents.

2.DATATYPES,CONSTANTSANDVARIABLES
TYPES
ThedataitemswhichappearinaFortran77programhaveatypeassociatedwiththem.Theallowed
typesare:
real
exponentandsignificantfractionstoredseparatelyknownasfloatingpointstorage
integer
storedasinteger
character
usedtostoretext,orcharacterstrings
logical
onlytwopossiblevaluesdenoted.TRUE.and.FALSE.
doubleprecision
like'real'butusestwicethenumberofbits
complex
equivalenttoapairof'reals'
CONSTANTS
Realconstantsarenumberscontainingadecimalpointand(optionally)precededbyasigne.g.
4.70.01+3.1415917..1

Theexponentformrepresentsrealconstantsbya(signed)number(themantissa),withorwithouta
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

3/30

3/14/2015

IntroductiontoFortranProgramming

decimalpoint,followedbythelettere(orE)andasecondnumber(theexponent),sotheprevious
examplescouldbewritten:
47E11E23.14159E00.17E21E1

Integerconstantsarenumberswhichdonotcontainanydecimalpointandwhichmay,optionally,be
precededbyasigne.g.
41+275

Integersuptoacertainsize(dependentupontheparticularcomputer)arestoredwithcomplete
precision.
Characterconstantsaresequencesofcharacters,knownasstrings,enclosedinsinglequotes,or
apostrophes,e.g.
'ComputationalPhysics''a4''aaaa'

Theapostrophesdonotformpartofthestringandarenotstoredinmemory,unlessrepeatede.g.'I
don''t'isastringcontainingasingleapostrophe.
VARIABLES
Fortranvariableshavenameswhichdenotestoragelocationsinmemory.ThestrictFortran77rules
fornamesarethatthey
muststartwithaletterofthealphabet
mustcontainonlyUPPERCASElettersordigits(knownasalphanumericcharacters)
mustbeatmost6characterslong
ParticularimplementationsofFortranmayrelaxtheserulese.g.inourexampleproj1.f,thereisa
variablecalledtheta_radwhichisclearlylongerthan6charactersandincludestheunderscore
character,butifyouwishyourcodetobeportablebetweendifferentmachinesyoushouldsticktothe
standard!
Variablenamescanbedeclaredbeforethefirstexecutablestatementofaprogram,e.g.
realx,height,range
integermonth,minute
character*9name,class,degree
logicaltest
doubleprecisionxplot,yplot

NOTEthatindeclaringacharactervariable,thelengthofthecharacterstringisspecifiedby
appending*followedbythenumberofcharactersinthestringtothetype.Intheaboveexample,
name,classanddegreearealldeclaredtobecharacterstringsoflength9.
IMPLICITTYPING
Fortran77hassomepotentiallydangerousrulesaboutvariabletypes.Ifavariablenameisused
withoutdeclaration,ITISASSUMEDTOBEREALifitsnamestartswithaletterintherangeahor
oz,whereasITISASSUMEDTOBEINTEGERifitstartsintherangein.
Someprogrammersadoptthepracticeofalwaysdeclaringallthevariablesusedinaprogram,
regardlessofwhetherornottheyconformtotheimplicittyping.Goingbacktoproj1.fweseethatx,
y,u,vx,vy,g,dt,theta,theta_rad,andpiarealldeclaredtobeoftypereal,whereasnstepand
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

4/30

3/14/2015

IntroductiontoFortranProgramming

max_stepsaredeclaredtobeoftypeinteger.Inthiscase,thedeclarationsconformtotheimplicit

typingrules.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!F90FEATURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Thestatement
implicitnone

atthestartofaprogramoverridestheimplicittypingofFortran77,requiringthatallvariablesthenbe
declaredexplicitly.Itsuseiswidelyregardedasgoodprogrammingpracticeandyouare
STRONGLYENCOURAGEDTOUSEIT.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

ClickhereifyouwishtoreturntotheTableofContents.

3.OPERATORS
ASSIGNMENTOPERATOR
Rememberthattheassignmentoperator,=,hasadifferentmeaningtotheusualarithmetic'equals'.
Thus
x=x+vx*dt

means'evaluatetheexpressionontherighthandsideusingthecurrentvaluesofthevariablesx,vx
anddt,andthenuseittooverwritethecurrentvalueofxi.e.storethevalueoftheexpressioninthe
memorylocationlabelledbyx'.
ARITHMETICOPERATORS
Thearithmeticoperatorsare
+/***

representing,respectively,addition,subtraction,division,multiplicationandexponentiation.Thefirst
fourappearexplicitlyinourexampleprogram,proj1.f.
Itisimportanttobeawarethatthereisanorderofprecedencefortheseoperatorswhichmaymatter
whenevaluatingcomplicatedexpressions.Thepriorityruleis:**hashighestpriorityfollowedby/
and*followedby+and
Withinanyoneprioritylevel,evaluationiscarriedoutfromlefttoright.Forexampleinthe
expression
3.0+4.0**2.08.0/4.0+2.0

exponentiationisperformedfirst,causingtheexpressiontoreduceto
3.0+16.08.0/4.0+2.0

followedbyanymultiplicationordivision,leadingto
3.0+16.02.0+2.0

http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

5/30

3/14/2015

IntroductiontoFortranProgramming

whichfinallyreducesto19.0.
Thereisoneimportantexceptiontotheleft>rightevaluationrule:multipleexponentiation.Thusfor
example
a**b**c

isevaluatedfromrighttoleft!
Ambiguitiescanalwaysberesolvedbytheuseofparentheses.Thusforexample,intheexpression
x+vx*dt

themultiplicationofvxanddtisperformedfirst,followedbytheadditionoftheresulttox.Hadwe
wishedfirsttoaddxtovxandthenmultiplybydtwecouldhavewritten
(x+vx)*dt

Ingeneral,ANYEXPRESSIONENCLOSEDINPARENTHESESISEVALUATEDFIRST.

Exercise:whatarethevaluesofthefollowingFortranexpressions?
5.+2.*3.(5.+2.)*3.2.*3.**3.(2.*3.)**3.2.**3.**2.

Intheevaluationofanarithmeticexpressionoftheform
operandoperatoroperand

inFortran77,oneoftherulesisthatbothoperandsmustbeofthesametype(otherthaninexpressions
involvingexponentiationoftheformx**2).Ifoneisanintegerandtheotherisareal(aMIXED
MODEexpression),thentheintegerwillbeconvertedtorealbeforetheoperationisperformed.The
resultisofthesametypeastheoperands.MIXEDMODEassignmentisalsopossiblebutshouldbe
usedwithcare.
Examples:
9*tempc/5

Heretempcisrealbydefault,so9isconvertedto9.0andthemultiplicationisperformedaccordingto
therulesofprecedencediscussedabove.Theresultisoftyperealandthusthedenominatorisfirst
convertedto5.0beforethedivisioniscarriedout,thefinalresultbeingoftypereal.
a=7*8

Bothoperandsonther.h.s.areoftypeinteger,sotheresultofthemultiplyis56,oftypeinteger.This
isthenassignedtoa,whichisbydefaultoftypereal,soatakesthevalue56.0
j=6.0*7.0/9.0

Herether.h.s.isarealexpressionwhichevaluatesto4.666...Thevalueassignedtotheintegerjis
then4,thefractionalpartbeingdiscarded(thisisknownastruncation).
*******************************
*Warningonintegerdivision*
*******************************

Anyfractionalpartremainingonintegerdivisionisalsodiscarded,whichcancatchouttheunwary
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

6/30

3/14/2015

IntroductiontoFortranProgramming

programmer!Forexample,
i=7
j=2
k=i/j

givesk=3.
Similarly
i=7
j=2
a=i/j

givesa=3.0,fromtherulesformixedmodeassignment.
TYPECONVERSIONOPERATORS
Typeconversionispossibleusingtypeconversionoperatorsthusappliedtothepreviousexample
i=7
j=2
a=real(i)/real(j)

givesa=3.5,whichisprobablywhatyouintended!
Itisalsopossibletoconvertfromtyperealtotypeintegerint(a)yieldsanintegerresult,theinteger
partofa.
RELATIONALOPERATORS
Inproj1.fyouseeanexampleofacomparator,orrelationaloperator,whichisusedintheline
dowhile(y.ge.0.0)

totestwhetherornotyisgreaterthanorequaltozero.Theexpressiony.ge.0.0iscalledarelational
expressionbecauseitexpressesarelationbetweentwovalues.Therearesixrelationaloperatorsin
Fortranwhichmaybeusedtoconstructrelationalexpressionsoftype'logical'whichareeithertrueor
falsethatis,theycorrespondinvaluetooneofthetwological(orBoolean)constants.TRUE.or
.FALSE.

Thecompletesetofrelationaloperatorsisasfollows:
a.lt.b

evaluatesto.TRUE.ifaislessthanb,otherwise.FALSE.

a.le.b

evaluatesto.TRUE.ifaislessthanorequaltob,otherwise.FALSE.

a.gt.b

evaluatesto.TRUE.ifaisgreaterthanb,otherwise.FALSE.

a.ge.b

evaluatesto.TRUE.ifaisgreaterthanorequaltob,otherwise.FALSE.

a.eq.b

evaluatesto.TRUE.ifaisequaltob,otherwise.FALSE.

a.ne.b

evaluatesto.TRUE.ifaisnotequaltob,otherwise.FALSE.

******************************
*Warningoncomparingreals*
******************************
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

7/30

3/14/2015

IntroductiontoFortranProgramming

Itcanbedangeroustousetherelationaloperators.ne.and.eq.forcomparingrealsbecauseof
roundingerrors.Forexample,infiniteprecision,1./3.hasthevalue0.3333333,say,sothat3.0*
(1.0/3.0)hasthevalue0.9999999NOT1.0,sothatthecomparison
3.0*(1.0/3.0).eq.1.0

evaluatesto.FALSE.insteadof.TRUE.
LOGICALOPERATORS
Relationaloperatorsareusedtocreatealogicalexpression,whichtakesthevalue.TRUE.or.FALSE.
logicalexpressionscanbecombinedusinglogicaloperatorstoperformmoresophisticatedlogical
tests.Thelogicaloperatorsare
.AND..OR..EQV..NEQV..NOT.

andtheiruseisillustratedbythefollowingtable,whereL1andL2arelogicalexpressions
L1L2L1.OR.L2L1.AND.L2L1.EQV.L2L1.NEQV.L2

.TRUE..TRUE..TRUE..TRUE..TRUE..FALSE.
.TRUE..FALSE..TRUE..FALSE..FALSE..TRUE.
.FALSE..TRUE..TRUE..FALSE..FALSE..TRUE.
.FALSE..FALSE..FALSE..FALSE..TRUE..FALSE.

Thus.OR.givesaresultthatisonlytrueifeitherofitsoperandsistrue,whereas.AND.givestheresult
trueonlyifbothoperandsaretrue.
.EQV.givesatrueresultonlyifbothL1andL2arelogicallythesamevalue,whilst.NEQV.givesatrue
resultifL1andL2haveoppositevalues.Theymaybeusedtosimplifymorecomplexlogical

expressionse.g.thefollowingtwoexpressionshavethesamevalue:
(a.lt.b.AND.x.lt.y).OR.(a.ge.b.AND.x.ge.y)a.lt.b.EQV.x.lt.y

Theremainingoperator,.NOT.,takesonlyasingleoperand,whosevalueitinverts.Forexample,the
followingtwoexpressionsareequivalent:
.NOT.(a.lt.b.EQV.x.lt.y)a.lt.b.NEQV.x.lt.y

Priorityrulesforlogicaloperatorsapplyjustastheydidforarithmeticoperators:
OperatorPriority

.NOT.1(high)
.AND.2
.OR.3
.EQV./.NEQV.4(low)

Asbefore,parenthesesmaybeusedtomaketheorderofevaluationclear.
CHARACTEROPERATOR
Thereisonlyonecharacteroperator,theconcatenationoperator//,whichcanbeusedtocombinetwo
stringstoformathirdstring.Forexample:
'Wed'//'nesday'isequivalenttothestring'Wednesday'
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

8/30

3/14/2015

IntroductiontoFortranProgramming

INITIALVALUES
Oftenweneedtoassignaninitialvaluetosomeorallofthevariablesinaprogram.Fortran77allows
ustodothisbymeansofthedatastatement,whichtakestheform:
data'namelist1'/'clist1','namelist2'/'clist2',........

or
data'namelist1'/'clist1'/'namelist2'/'clist2'.........

where'namelist*'isalistofvariablesnamesand'clist*'isalistofconstantvalues,withthesame
numberofitemsasthecorresponding'namelist'.Theeffectistogiveeachvariablein'namelist'the
initialvaluespecifiedbythecorrespondingitemin'clist'.Thenormalrulesofarithmeticapplyand
theconstantwillbetypeconvertedifnecessarytomatchthetypeofthevariable.Note:thequotation
marksarenotpartofthesytax.
Example:
dataa,b,n/1.0,2.0,3/,code/8667.0/

givestherealvariablesaandbinitialvaluesof1.0and2.0,theintegervariablenaninitialvalueof3,
andtherealvariablecodeaninitialvalueof8667.0.
Severalitemscanbegiventhesameinitialvaluebyprecedingtheconstantbyarepetitioncounte.g.
datai,j,k,l,m,n/6*0/

AdatastatementmustappearAFTERanyspecificationstatements.Itisusual,butnotnecessaryto
putdatastatementsatthebeginningoftheexecutablepartoftheprogram.
*****************************
*Warningoninitialvalues*
*****************************

Manycomputersystemsinitialiseallvariablestoapredefinedvalue,usually0,butITISNEVER
SAFEtoassumethatthisisthecase.
NAMINGCONSTANTS
Althoughthedatastatementcanbeusedtogiveavaluetoavariablethatisneverchangede.g.
datapi/3.14159/

thereisapreferredwayofnamingconstants,whichistousetheparameterstatement.Ittakesthe
form
parameter('name1'='const1','name2'='const2',......)

withobviousmeaning.Thuswecouldwrite
parameter(pi=3.14159)

Thenoneveryoccasionthatpiisreferredtointheprogram,thevalue3.14159willbeused.
Constantexpressionscanalsobeusede.g.
parameter(third=1.0/3.0,pi3by4=3.0*pi/4.0)

Whereanexpressionisusedtherearesomerestrictions:
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

9/30

3/14/2015

IntroductiontoFortranProgramming

onlytheoperators+,,/and*maybeused,exceptthat**maybeusedaslongasthe
exponentisanintegerparenthesesmaybeusedasnormal
ifanamed(orsymbolic)constantappearsinaconstantexpressionitmusthavebeendefinedby
anearlier'parameter'statement,orinanearlierpartofthecurrentstatement.
ClickhereifyouwishtoreturntotheTableofContents.

4.TASKREPETITIONUSINGDOLOOPS
THEDOLOOP
TherepetitionofanumberofstatementsapredeterminednumberoftimesissoimportantthatFortran
containsaspecialconstructthatallowsthistobedone.Ingeneral,a"doloop"maycontainany
Fortranstatements,includinganotherdostatement,knownasa"nesteddoloop".
!!!!!!!!!!!!!!!!!!F90FEATURE:the'enddo'statement!!!!!!!!!!!!!!!!!!!!!!!!

Fortran90denotestheterminatingstatementofa"doloop"bymeansoftheenddostatement.
Thesyntaxis:
doindex=int1,int2[,int3]
'statements'
enddo

where:
indexisNORMALLYanintegervariable,butMAYBEOFTYPEREALtheuseofreal"do

loop"indicesisDISCOURAGED
int*arevariablesorexpressions,convertedifnecessarytotheSAMETYPEasindex.index
startsatint1,andisincrementedbyint3attheendoftheloop.int2isusuallythefinalvalue
ofindex,althoughthisisnotalwaysso.

Note:Thenotation[,int3]simplymeansthatint3isoptionalitisassumedtobe1ifomitted.The
squarebracketsarenotpartofthesyntax!
Thenumberoftimesthatthebodyofthe"doloop",denotedby'statements',isexecuted(knownas
the"tripcount")iscalculatedfromtheformula:
MAX(0,INT((int2int1+int3)/int3))

whereINTdenotestheintegerpartoftheensuingexpression.ThisnumberiscalculatedBEFOREthe
loopstarts.Ifzero,itmeansthatthebodyofthe"doloop"isNOTexecuted.
Examples:
doi=0,100,5

hasatripcountof21whereas
doi=0,100,9

hasatripcountof12
Example:averysimpleprogramtocomputethesquaresoftheintegersfrom1to10,andprintthem
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

10/30

3/14/2015

IntroductiontoFortranProgramming

out.
programsquares
c
caprogramtocalculatethesquaresofthefirsttenintegers
c
implicitnone
integerint,intsq
doint=1,10
intsq=int*int
write(*,*)'Thesquareof',int,'=',intsq
enddo
stop
end

RESTRICTIONS
the"do"variable,index,mustNOTbealteredwithinthe"doloop",althoughitsvaluemaybe
usedinanexpression
the"do"variableisupdatedattheendofeachpassthroughtheloop,butbeforeadecisionis
madeaboutanotherpassthismayhaveimplicationsifyouwishtousethevalueofindexlater
inyourprogram
itisnotpermissibletojumpintothebodyofa"doloop"althoughjumpsoutareallowed
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

TheFortran77syntaxinvolvestheuseofalabelledstatementtodenotetheendoftheloopandis:
dom,index=int1,int2[,int3]
'statements'
mcontinue

where:
misastatementlabel(anintegerintherange199999)
indexisnormallyanintegervariable,butMAYBEOFTYPEREAL
int*arevariablesorexpressions,convertedifnecessarytotheSAMETYPEasindex

Note:thecommaafterminthedostatementisoptionalyoumayencounterbothforms.
THEDOWHILELOOP
!!!!!!!!!!!!!!!!!!!!F90FEATURE:the'dowhile'construct!!!!!!!!!!!!!!!!!!!

Thereisanexampleofa"dowhileloop"inproj1.f.Thisconstructpermitstherepeatedexecutionof
oneormoreFortranstatementsconditionaluponthestatusofalogicalexpression,ratherthanfora
fixednumberofrepetitions.Thesyntaxis:
dowhile('logicalexpression')
'statements'
enddo

whichloopsthrough'statements'foraslongas'logicalexpression'evaluatesto.TRUE.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

11/30

3/14/2015

IntroductiontoFortranProgramming

Exercise:GototheWORKERWINDOWandusetheeditortowriteaprogram
toprintoutthefactorialofn(aninteger)fromn=1to20.NOTE:the
filenamethatyouuseforstoringyourprogrammusthavethedefault
extension.fotherwiseitwillnotberecognisedbythecompiler,souse
somethinglike
uefact.f
Yourprogramshouldnotusemorethanone"doloop".Trycompilingand
runningyourprogram.Whatgoeswrongifyouuseintegervariablesin
yourprogram??
Remember,thecommandwhichinvokesthecompileris
f77'filename'
whichproducesanexecutablefilecalleda.out

orf77o'file2''file1'
ifyouwanttheexecutabletobecalled'file2'.(Donottypethequote
marks!).Torunyourprogram,simplytypethenameoftheexecutablefile.
***CHECKPOINT1***

ClickhereifyouwishtoreturntotheTableofContents.

5.CONDITIONALCONSTRUCTS
SIMPLEIF
TherearetwoformsoftheIFconstruct.Thesimpleform(whichis,strictlyspeaking,ahangoverfrom
earlierversionsofFortran)is:
if('logicalexpression')'statement'

Here'statement'isanyexecutablestatementandisonlyimplementedif'logicalexpression'has
thevalue.TRUE.
Example:
if(volts.gt.threshold)signal=gain*input

BLOCKIF
ThereisalsoablockIFconstruct:
if('logicalexpression1')then
'statements1'
elseif('logicalexpression2')then
'statements2'
elseif('logicalexpression3')then
'statements3'
else
'statements4'
endif
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

12/30

3/14/2015

IntroductiontoFortranProgramming

Here'statements*'areblocksofoneormorelinesofFortran.Onlyoneblockgetsexecutedina
particularrune.g.'logicalexpression2'isonlytestedif'logicalexpression1'hasthevalue
.FALSE.andsoon.
Anynumber,includingzero,ofelseifblockscanbeusedandthefinal"catchall"elseblockcanbe
omitted.Thusthesimplestformis
if('logicalexpression1')then
'statements1'
endif

whichisequivalenttothesimpleformdescribedaboveinthecasewhere'statements1'consistsof
justasinglestatement.
Example:aprogramtocomputethenumberofpointswithpositiveintegercoordinatesinsidethe
ellipsex**2/16+y**2/25=1
programellipse
c
cdeclarations
c
implicitnone
integernpts,ix,iy
c
cinitialisecounter
c
npts=0
c
cloopoverxdirection
c
doix=1,4
c
cloopoverydirection
c
doiy=1,5
c
ctesttoseeifpointlieswithinellipse
c
if(real(ix*ix)/16.0+real(iy*iy)/25.0.lt.1.0)then
npts=npts+1
endif
enddo
enddo
write(*,*)'Numberofpoints:',npts
stop
end

Notetheuseofthe"programstatement"notessential,butgoodprogrammingpractice.Thenameof
theprogrammaybefreelychosen,withintheFortrannamingconventions.
Notethatindentationhasbeenusedtoclarifytheloopstructure,althoughnotnecessarythecontents
ofeach"doloop"areindentedbytwospaceswithrespecttothedoandenddostatements,asarethe
contentsoftheifblock.

Exercise:gototheWORKERwindowandgetacopyoftheellipseprogramby
typing
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

13/30

3/14/2015

IntroductiontoFortranProgramming

cp/usr/local/text/cplabwork/examples/fortprogs/ellipse.fellipse.f
Trycompilingandrunningthisprogram.Remember,thecommandwhichinvokes
thecompileris
f77'filename'
whichproducesanexecutablefilecalleda.out

orf77o'file2''file1'
ifyouwanttheexecutabletobecalled'file2'.(Donottypethequote
marks!).Torunyourprogram,simplytypethenameoftheexecutablefile.

Example:aprogramtoreadpositiveintegersandcomputetheiraveragenegativeintegersare
ignoredwhilstzeroterminatestheprogram.
programaverage
csummary:programtoreadpositiveintegersandfindtheiraverage,
cignoringnegativeintegersandterminatingonzero
cvariabledefinitions:
cnumintnumberofintegersreadinsofar
cintsumrunningtotalofintegervalues
cintcurrentinteger
cnfordoloopcontrol
c
cdeclarations
c
implicitnone
integernumint,intsum,int,n
c
cinitialisecounterandtotal
c
numint=0
intsum=0
n=1
dowhile(n.eq.1)
c
cinputintegerfromkeyboard
c
write(*,*)'Inputinteger'
read(*,*)int
c
ctestfornegativeorzerovalues
c
if(int.gt.0)then
numint=numint+1
intsum=intsum+int
elseif(int.eq.0)then
write(*,*)'Numberofpositiveintegers:',numint,
&'Average:',real(intsum)/real(numint)
stop
endif
enddo
end

http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

14/30

3/14/2015

IntroductiontoFortranProgramming

Notethecontinuationline,denotedby'&'incolumn6.
Notethedifferencebetweenthestopstatement,whichsignifiesthelogicalendoftheprogramand
terminatesexecution,andtheendstatement,whichdenotesthephysicalendoftheprogram.Any
programthatyouwritemusthaveanendstatementasitsfinalstatement,oritwillnotcompile.It
shouldalsohaveastopstatement,althoughitmaywellcompileandrunwithoutone.

Exercise:Getacopyoftheaverageprogram:
cp/usr/local/text/cplabwork/examples/fortprogs/aver.faver.f
andtryitout.

ClickhereifyouwishtoreturntotheTableofContents.

6.ARRAYS
Itisoftendesirabletorefertoagroupofrelateditemsofthesametypebygivingthemthesame
groupname,andidentifyingtheindividualitemsbytheirpositionswithintheset.Arraysareusedfor
thispurposeinFortran.
Eachitemwithinanarrayisreferredtoasanarrayelementandisidentifiedbyanintegerindexor
subscriptwhichfollowsthearraynameinparentheses.Anarrayisalwaysdeclaredinanextended
typedeclarationstatement,whichalsodeclarestherangeofpossiblesubscripts,andhencethesizeof
thearray.Forexample
integern(100)

reserves100integerlocationsinmemorycalledn(1),n(2),n(3),.....n(100).Instatementswhich
referenceanarrayelement,theindexorsubscriptmaybeanyintegerexpressione.g.n(3*j+2).
Arrayelementsmaybeusedanywherethatavariablenamecanbeused,butareespeciallyusefulin
conjunctionwitha"doloop",whoseindexcanbeusedasanarraysubscript,enablingeachpass
throughthelooptouseadifferentarrayelement.
Example:herearethebarebonesofaprogramtofindthelargestelementofanarrayoftenintegers.
Youareinvitedtocompleteit:
programlargest
c
cvariables:
c
civecarraytoholdnumbers
clargelargestarrayelement
cjlabelslargestarrayelement
cidoloopindex
c
cdeclarations
c
implicitnone
integerivec(10),large,i,j
c
cinputthearrayelements
c
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

15/30

3/14/2015

IntroductiontoFortranProgramming

write(*,*)'Enter10integers,oneperline:'
read(*,*)(ivec(i),i=1,10)
c
cstartbyassumingfirstelementtobelargest....
c
large=ivec(1)
j=1
doi=2,10
c
cnowwritetherestofthisloopyourself........
c
enddo
write(*,*)'Element',j,'islargestandhasvalue',large
stop
end

Note:inthisexampletheuseofasocalled"implieddoloop"inthereadstatementwhichinputsthe
tenelementsofthearrayivecinsequence.

Exercise:gettheskeletonprogram
cp/usr/local/text/cplabwork/examples/fortprogs/largest.flargest.f
andtrytocompleteit;checkyourprogrambycompilingandrunningit.
***CHECKPOINT2***

Bydefault,arraysubscriptsinFortranstartat1,butthiscanbeoverriddenforexample
realv(4:3)

declaresarealarraywith8elementsv(4),v(3),.....v(3)Thefirstexamplecouldequallywell
havebeenwritten
integern(1:100)

MULTIDIMENSIONALARRAYS
Therearemanyinstanceswhereitisusefultobeabletodeclareanarraywithmorethanone
subscriptforexample,tostorethevaluesoftheelectrostaticpotentialatpointsinthexyplane.
Fortran77allowsustohaveuptosevensubscriptsforasinglearray.Thenumberofsubscriptsis
referredtoastheDIMENSIONofthearray.
Examples:
realpotl(100,100)
integerpressure(20,40,30)

Thefirstofthesecouldequallywellbewritten
realpotl(1:100,1:100)
or
realpotl(1:100,100)
or
realpotl(100,1:100)

Anelementofamultidimensionalarraymustalwaysbereferredtowiththecorrectnumberof
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

16/30

3/14/2015

IntroductiontoFortranProgramming

subscriptsandcan,ofcourse,beusedinexactlythesamewayasavariableoranelementofaone
dimensionalarray.
Arraysmayhavecharactersratherthannumbersaselements,forexample,wemightwanttoprocessa
setofnamesofstudentsbytutorialgroupandserialnumberwithinthegroup:
programnamelist
c
cvariabledefinitions:
c
cigrouplabelsagroup
cidentlabelsanindividual
cnamestoresnamesinrequiredorder
cnextnextnameinsequence
c
cone'*'terminatesagroup
ctwo'**'terminatesthewholedataset
c
cdeclarations
c
implicitnone
character*15name(30,10),next
integerigroup,ident
igroup=1
10ident=1
20read(5,*)next
if(next.eq.'*')then
igroup=igroup+1
goto10
elseif(next.ne.'**')then
name(ident,igroup)=next
ident=ident+1
goto20
endif
cnowprocessthedatainthearrayname............

Notetheuseofthegotostatementtogetherwithstatementlabels,totransferprogramcontrol
conditionally.TheuseofthegotoisSTRONGLYDISCOURAGEDasitmakesprogramlogic
difficulttofollowandcanleadtopoorlystructuredcode.

Exercise:canyoudeviseawayofaavoidingtheuseof"goto"statementsand
statementlabelsinthepreviousexample,usingtheF90constructsthatyou
havealreadymet?

Wecanuseanimplieddolooptoinputtooroutputfromapart,orthewholeofamultidimensional
arraye.g.
read(5,*)((potl(i,j),i=2,25),j=10,50)
****************************
*Warningonstorageorder*
****************************

Theelementsofaonedimensionalarrayoccupyconsecutivestoragelocationsinmemorybutitisnot
immediatelyobviouswhathappenswithhigherdimensionalarrays.InfactinFortran,multi
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

17/30

3/14/2015

IntroductiontoFortranProgramming

dimensionalarraysarestoredinsuchawaythatthefirstsubscriptchangesmostrapidlye.g.the
elementsof
integermat(3,3)

arestoredwithmat(1,1),mat(2,1),mat(3,1),mat(1,2),......inconsecutivelocationsinmemory.
Thisisimportanttoknowifyouwishtooptimisethespeedofexecutionofaprogramthat
manipulatesarrays.Thusintheexampleaboveontheuseofimplieddoloopstoreadintoatwo
dimensionalarrayitwouldbelessefficienttowrite
read(5,*)((potl(i,j),j=10,50),i=2,25)

becausetheinnermostloopisaccessingelementswhichdonotcorrespondtoconsecutivelocationsin
memory.
ClickhereifyouwishtoreturntotheTableofContents.

7.INPUT/OUTPUT
TERMINALI/O
Thesimplestformofinputandoutput,whichutilisesonlythekeyboardandscreenofyourterminal,
isknownaslistdirected.Youhavealreadymetexamplesintheprogramproj1.f.Infactthat
programdidnotmakeuseoftheverysimplestformswhichwenowdescribe.
LISTDIRECTEDOUTPUT
uses
print*,'expressionlist'
or
write(*,*)'expressionlist'
or
write(6,*)'expressionlist'

Inthethirdform,6denotesthedefaultoutputdevice,theterminalscreen,forhistoricalreasons.Itis
betterandsafertousethesecondforminwhich*denotesthedefaultdevice.
Thevaluesofanyliterals,variables,constantsorexpressionsin'expressionlist'willbeprintedin
theorderinwhichtheyarelisted.Theformofnumericoutputispredeterminedbythecompiler.
Examples:
print*,'Distanceversusvelocity'
print*,'Slope=',slope
write(*,*)'Specifylaunchspeedu(m/sec):'

LISTDIRECTEDINPUT
uses
read*,'variablelist'
or
read(*,*)'variablelist'
or
read(5,*)'variablelist'
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

18/30

3/14/2015

IntroductiontoFortranProgramming

Here5denotesthedefaultinputdevice,theterminalkeyboard,againforhistoricalreasons.The
secondformispreferred.
Valuesarestoredintheorderinwhichthevariablesarelisted.Datavaluesmustbeseparatedby
commasorblanks.Asmanylinesasareneededwillberead.Eachread*statementwillbegin
searchingforvalueswithanewline.
Examples:
read*,time
read*,(x(j),j=1,100)
read(*,*)theta

Exercise:Writeaprogramtoreadinaandb,thesidesofarectangle,
andprintouttheperimeterandarea.
***CHECKPOINT3***

Wemaywishtoexercisemorecontrolovertheappearanceofouroutputthanisaffordedbythelist
directedformsjustdescribed.Fortranmakesprovisionfortheuseof'formatdescriptors'toachieve
usercontroloverbothinputandoutput.
FORMATTEDOUTPUT
tothedefaultoutputdeviceuses
printk,'expressionlist'
or
write(*,k)'expressionlist'
or
write(6,k)'expressionlist'

Thevaluesofanyvariablesorexpressionsin'expressionlist'willbeprintedintheorderinwhich
theyarelistedaccordingtothespecificationsinaformatstatementwithlabelk.Wewilldiscuss
formatinSection8.
Examples:
print100,alpha,beta
print50
write(*,99)x,(a(i),i=1,6)

Thislastexampleagainillustratesuseoftheimplieddolooptoprintoutelementsofanarray.
FORMATTEDINPUT
fromthedefaultinputdeviceuses
readk,'expressionlist'
or
read(*,k)'expressionlist'
or
read(5,k)'expressionlist'

Thevaluesofanyvariablesorexpressionsinexpressionlistwillbeinputintheorderinwhichthey
arelistedaccordingtothespecificationsinaformatstatementwithlabelk.Wewilldiscussformatin
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

19/30

3/14/2015

IntroductiontoFortranProgramming

Section8.
Examples:
read200,alpha,beta
read(*,99)x,(a(i),i=1,6)

FILEI/O
Wemaywishmoregenerallytoreadfrom,orwritetofilesratherthanthestandardinputandoutput
deviceskeyboardandscreen.YoumayalreadyhavetrieddoingthisintheIntroductoryCourse
ProgrammingExercises.ThewayinwhichthisisdoneinFortran77isbymeansoftheopen
statement,whoseformis
open('olist')

where'olist'isalistofopenspecifierschosenfromthefollowingset:
unit=u,file=fn,status=st,access=acc,form=fm,err=s,iostat=ios

Thefirstofthese,unit,MUSTBEPRESENT,theothersarealloptional.Theunitspecifiertakesthe
sameformasinthereadandwritestatementsdiscussedabove,andprovideditisfirstinthelist,the
stringunit=maybeomitted,withonlyanintegervalue,u,specifyingtheunitnumber.
Weshallnotconsiderthefullgeneralityoftheopenstatementherebutrestrictconsiderationtothe
followingform:

open(unit=integerexpression,file='filename',status='literal')

designatesthefilenamed'filename'forallinputoroutputstatementsthatrefertotheunitnumber
specifiedbythevalueofintegerexpression.
Ifthestring'literal'is'old',thefilemustbeanexistingoneif'literal'is'new',thefilemust
NOTbeanexistingone.Ifafilewhosestatusis'new'issuccessfullyopened,itsstatusisthereby
changedto'old'andanysubsequentattemptstoopenthefileas'new'willfail.
'literal'mayalsobe'unknown',whichisequivalenttoomittingthestatusspecifierandis

implementationdependent,or'scratch'foratemporaryfilewhichisdeletedwhenexecutionfinishes.
Examples:
open(8,file='projdata')
open(unit=15,file='data/run.1',status='old')
open(unit=10,file='latest',status='new')

Eachopenstatementshouldbematchedbyacorrespondingclosestatement,oncetheunitinquestion
isnolongerneededbytheprogram:
Examples:
close(8)
close(unit=15)
close(unit=10)

LISTDIRECTEDINPUT
thenuses
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

20/30

3/14/2015

IntroductiontoFortranProgramming

read(unitnumber,*,end=n)'variablelist'

toreadfromthedatafilereferencedbyunitnumber,whichmustcorrespondtoaunitnumber
assignedtoafilebyapreviousopenstatement,exceptforthecasewhereunitnumberis5,whichis
bydefaulttheterminalkeyboard.*denoteslistdirectedinput.end=nisoptionalandwillcausecontrol
topasstostatementnifthereadstatementisexecutedafterthelastlineofdatahasbeenread.
Examples:
read(15,*,end=200)x,y,z
read(11,*)i,j,k,l

FORMATTEDINPUT
uses
read(unitnumber,k,end=n)'variablelist'

toreadusingtheformatstatementlabelledk.end=nisoptional,asbefore.
Example:
read(15,99,end=200)u,v,w

LISTDIRECTEDOUTPUT
uses
write(unitnumber,*)'variablelist'

towritedatatoafilespecifiedbyunitnumber,whichmusthavebeenassignedinanopenstatement,
exceptwhenunitnumberis6whichisbydefaulttheterminalscreen.
Example:
write(13,*)a,b,c

FORMATTEDOUTPUT
uses
write(unitnumber,k)'variablelist'

towritedatatoafilespecifiedbyunitnumber,whichmusthavebeenassignedinanopenstatement,
usingtheformatstatementlabelledk.
Example:
write(8,100)a,(r(k),k=1,20)

ClickhereifyouwishtoreturntotheTableofContents.

8.FORMAT
{{{OPTIONAL
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

21/30

3/14/2015

IntroductiontoFortranProgramming

Thissectionshouldprobablyberegardedasoptionalifyouaredoingthistutorialforthefirsttime.If
youfindithardgoing,skiptosection9.Themostreadablewaytospecifytheformatinwhichdatais
tobeinputoroutputisbymeansofthe"format"statement,referredtointheprevioussection.The
generalformoftheformatstatementis:
kformat('formatdescriptor')

where'formatdescriptor'isacharacterexpressionandkisastatementlabel.Formatstatementscan
appearanywhereinaprogramapopularchoiceistogatherthemalltogetherjustbeforetheend
statement.
FormatisjustaboutthehardestthingtogetrightinaFortranprogram,soletusstartwithasimple
example!
print100,max,res
100format(1x,i5,f9.3)

Theformatdescriptorconsistsofalistofformatcodes,withthefollowingmeanings:
nxdenotesnspacesherenis1
iwisINTEGERformat,printedinafieldofwidthwcharacterswis5
fw.disREALformat,printedinafieldofwidthw(includingthedecimalpoint),withddigits
afterthedecimalpointherewis9anddis3.

Thusif,forexample,max=12345andres=12345.678wewouldgetthefollowingoutput:
1234512345.678

whichisnotveryreadable!
Ontheotherhand,ifsaymax=1andres=2.0wewouldget
12.000

Yourprogrammaycrashifyoutrytoprinttoolargeanumberforthefieldwidththusmax=876543
istoobigfortheformatcodei5.
OUTPUTFORMATCODES
Hereisatabledescribingtheeffectsofvariousformatcodesforoutput:
codemeaning

iwoutputanintegerinthenextwcharacterpositions
fw.doutputarealinthenextwpositionswithddecimalplaces
ew.doutputarealinthenextwcharactersusingascientific
notationwithddecimalplacesinthemantissaandfour
characters(includingeandapossiblesign)intheexponent
dw.dasew.dbutfordoubleprecisionnumbers
gw.dsameasfw.difthereisroom,otherwiseew.d
nxignorethenextncharacterpositionsi.e.outputnblanks
anoutputcharacterexpressioninafieldofwidthw,truncating
orpaddingwithspacesasnecessary;fortruncationnleftmost
charactersareoutput;paddingisonleft
aoutputcharacterexpressioninafieldofitsownwidth
tcoutputnextitemstartingincharacterpositionc
tlnoutputnextitemstartingncharacterpositionsbefore(tl)or
trnafter(tr)thecurrentposition
'abcd..'outputthestringofcharacters'abcd..'startingatthenext
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

22/30

3/14/2015

IntroductiontoFortranProgramming

characterposition

Youcanusearepetitioncountformultipleinstancesofthesameformatcodeorcodesinaformat
statemente.g.
10format(1x,3i5,2(4x,a4))

isequivalentto
10format(1x,i5,i5,i5,4x,a4,4x,a4)

Separatorsinthelistofformatcodescanbeoftwokinds:
thecomma,thesimpleseparatorwehaveusedinallexamplessofar
theslash,/,themultirecordseparator,whichproducesanewline
Example:
print100,max,res
100format(1x,i5/f9.3)

withmax=12345andres=12345.678asinthefirstexample,wouldproduce
12345
12345.678

Whathappensifthereisamismatchbetweenthenumberofitemsintheoutputlistandthenumber
offormatcodes?
a)excesscodesareignored,forexample,
print100,jj
100format('a=',i3,'b=',i3)

ifjj=123wouldproduce
a=123b=

b)iftherearetoofewcodes,anewlineistaken,andthecodesarerepeatedfromtheleftparenthesis
correspondingtotheLASTBUTONErighthandparenthesis!Forexample,
print100,(a(i),i=1,80)
100format('Results:'/(1x,10f7.3))

givesaheaderlinefollowedby8linesof10items.However,
print100,(a(i),i=1,80)
100format('Results:'/1x,10f7.3)

wouldgive8pairsoflines,eachwithResults:onthefirstlineand10itemsonthenext.
CARRIAGECONTROLORFORMATEFFECTORS
IftheoutputfromaFortranprogramgoestoalineprinter,ortoafilewhichthengetsprintedona
lineprinter,thenthefirstcharacterineachlineisnotprinted,butisusedfor"carriagecontrol"orasa
"formateffector".
Theallowedformateffectorsareasfollows:
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

23/30

3/14/2015

IntroductiontoFortranProgramming

charactereffect

spacenoextraactioni.e.singlespacing
0skipanextralinei.e.doublespacing
1newpage
+overprintthelastline(notalwaysimplemented)

Asanexample
100format('1Results:'/(1x,10f7.3))

startsprintingonanewpage.
INPUTFORMATCODES
Mostoftheoutputformatcodesdescribedaboveareavailableasinputformatcodesbutarenot
widelyused,asfreeformat(denotedby*)dealswithmostsituations:
codemeaning

iwreadthenextwcharactersasaninteger
fw.dreadthenextwcharactersasarealwithddecimalplaces
ifnodecimalpointispresent;otherwiseignored
ew.dsameasfw.doninput
dw.dsameasfw.doninput
gw.dsameasfw.doninput
nxignorethenextncharacters
anreadnextncharactersascharacters;ifnislessthanlength
ofinputlistitempadwithblanks;innisgreaterthan
length,storerightmostcharactersofinputstringinitem
areadsufficientcharacterstofillinputlistitem
tcnextcharactertobereadisatpositionc
tlnnextcharactertobereadisncharactersbefore(tl)or
trnafter(tr)thecurrentposition

Thetreatmentofrealsbyfw.d(orew.d)perhapsneedsanexampletoclarify
read100,a,b,c,d
100format(f3.1,f2.2,f3.2,f1.0)

thentheresultfortwodifferentexamplesisasfollows:
dataabcd

12345678912.3.456.789.
.23.56.80.230.56.8

}}}
ClickhereifyouwishtoreturntotheTableofContents.

9.SUBPROGRAMS
Subprograms,orprocedures,arethebasicbuildingblocksofgoodFortranprograms(inthejargon,
WELLSTRUCTUREDPROGRAMS).Therearetwotypesofprocedureorsubprogram:subroutines
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

24/30

3/14/2015

IntroductiontoFortranProgramming

andfunctions.AcompleteFortranprogramconsistsofamainprogramandanynumberof
subprogramprogramunits.
INTRINSICFUNCTIONS
Fortrancontainsalibraryofintrinsicfunctionsprovidingthecommonlyusedmathematicalfunctions
suchasthetrigonometricfunctions,whichyouhavealreadymetintheexampleprogramproj1.f.
Youcanalsowriteyourownfunctionstosupplementorreplacethoseprovidedaspartofthe
language.Thekeyfeatureofafunctionsubprogramisthatitreturnsaresultthroughitsname,
whereassubroutinesubprogramsdonot.Generallyafunctiontakesoneormoreargumentsand
returnsaresult.
Hereisanexampleofanintrinsicfunction,thesquareroot,beingusedtocalculatetheareaofa
triangleofsidesa,b,cfromtheformula
area=squareroot{s(sa)(sb)(sc)}

where2sisthesumofthelengthsofthesides:
programtriangle
cvariabledefinitions:
ca,b,csidesoftriangle
cs(a+b+c)/2
careaareaoftriangle
c
cdeclarations
c
implicitnone
reala,b,c,s,area
c
creadthelengthsofthesidesofthetriangle
c
write(*,*)'Inputsidesa,b,c:'
read(*,*)a,b,c
c
ccomputeareausingintrinsicfunctionsqrt
c
s=0.5*(a+b+c)
area=sqrt(s*(sa)*(sb)*(sc))
write(*,100)area
100format(1x,'Areaoftriangleis:',f10.4)
stop
end

Exercise:trymodifyingthetriangleprogramtocheckthattheinput
valuesofa,bandcdoindeedcorrespondtoavalidtriangle,thatis,
theyareallnonnegativeandthesumofanytwoisgreaterthanthe
third.Asusualyoucangetacopybymeansofthecommand
cp/usr/local/text/cplabwork/examples/fortprogs/triangle.ftriangle.f
***CHECKPOINT4***

http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

25/30

3/14/2015

IntroductiontoFortranProgramming

FUNCTIONSUBPROGRAMS
Functionsubprogramsarealsoknownasexternalfunctionstodistinguishthemfromintrinsic
functions.Hereisasimpleexample,afunctiontocalculatetheaverageoffivenumbers:
programmean
cuseafunctionsubprogramtocalculatethemeanofasetoffivenumbers
c
cdeclarations
c
implicitnone
reala1,a2,a3,a4,a5,av,avrage
c
cinputfiverealnumbers
c
write(*,*)'Inputfiverealnumbers:'
read(*,*)a1,a2,a3,a4,a5
c
cinstanceoffunction
c
av=avrage(a1,a2,a3,a4,a5)
write(*,100)av
100format('Averageoffivenumbersis:',1x,f10.4)
stop
end
cendofmainprogram
cdefinitionoffunctionsubprogram
realfunctionavrage(x1,x2,x3,x4,x5)
cthisfunctionreturnstheaverageofitsfivearguments
c
cdeclarations
c
implicitnone
realx1,x2,x3,x4,x5,sum
sum=x1+x2+x3+x4+x5
avrage=sum/5.0
return
end

Notes:
thefirststatementisaspecialfunctionstatementwhichtakesthegeneralform:
'type'function'name'('d1,'d2',.....)

where'type'isoptionalifomittedthetypeisdeterminedbytheusualFortranrulesfor'name'.
'd1','d2'etcaredummyargumentsthatrepresenttheactualargumentsthatwillbeusedwhen
thefunctionisused(inthejargon,referenced).
thepenultimatestatement,return,isanalogoustothestopstatementinthepreviousexamples,
exceptthatitdoesnotterminateprogramexecutionbutsimplythatofthefunctionsubprogram,
returningtotheplaceinthemainprogramfromwherethefunctionwasreferenced.
onefurtherobservationitispossibletowriteafunctionthathasnoargumentsneverthelessin
referencingthatfunctionbynameinthemainprogram,theparenthesesmustbeincluded,even
thoughtheargumentlistisemptye.g.
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

26/30

3/14/2015

IntroductiontoFortranProgramming

result=fun()

SUBROUTINESUBPROGRAMS
Asubroutinesubprogramhasthesameoverallstructureasafunctionsubprogramexceptthatthefirst
statementisasubroutinestatementratherthanafunctionstatement.Thechiefdifferenceliesinhow
theyarereferencedandhowtheirresultsarereturned.
Aswehavejustseen,afunctionisreferencedbywritingitsname,followedbyanyarguments
enclosedinparentheses.Controlisthentransferredfromthecurrentstatementtothestatements
containedwithinthefunction.Theexecutionofthefunctionusestheactualvaluesprovidedforits
arguments,substitutingthemforthedummyargumentsinthefunctiondefinition,andcalculatesa
value,thefunctionvalue,whichisthenavailableasthevalueofthefunctionreferenceinthemain
program.
Asubroutine,ontheotherhand,isaccessedbymeansofacallstatement,whichgivesthenameof
thesubroutineandalistofargumentswhichareusedtotransferinformationbetweenthemain
programandthesubroutine:
call'name'('arg1,'arg2',..............)

Thecallstatementtransferscontroltothesubprogram,whosestatementsareexecuteduntilareturn
statementisencountered,whencontrolreturnstothestatementimmediatelyfollowingthesubroutine
call.
Asasimpleexample,letusreworkthepreviousexampletouseasubroutineinsteadofafunction
subprogram:
programmean
cuseasubroutinesubprogramtocalculatethemeanofaset
coffivenumbers
c
cdeclarations
c
implicitnone
reala1,a2,a3,a4,a5,av
c
cinputfiverealnumbers
c
write(*,*)'Inputfiverealnumbers:'
read(*,*)a1,a2,a3,a4,a5
c
csubroutinecall
c
callavrage(a1,a2,a3,a4,a5,av)
write(*,100)av
100format('Averageoffivenumbersis:',1x,f10.4)
stop
end
c
cendofmainprogram
c
cdefinitionofsubroutinesubprogram
c
subroutineavrage(x1,x2,x3,x4,x5,xbar)
cthissubroutinereturnstheaverageofitsfirstfivearguments
cinthesixthargument
c
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

27/30

3/14/2015

IntroductiontoFortranProgramming

cdeclarations
c
implicitnone
realx1,x2,x3,x4,x5,sum,xbar
sum=x1+x2+x3+x4+x5
xbar=sum/5.0
return
end

Notes:
thenameofthesubroutine(avrageinthisexample)issimplyanidentifieritdoesnothavea
typeandcannotappearinatypespecificationstatement.
theactualarguments,a1,a2,a3,a4,a5,avreplacethedummyargumentsx1,x2,x3,x4,
x5,xbarwhichappearinthesubroutinedefinition.Theymustmatchinnumber,typeand
order.
someoftheargumentsareinputparameterstothesubroutinewhilstothersareoutput
parameters
thevariablesx1,x2,x3,x4,x5,xbarareLOCALtothesubprogram.Thuswhenwritinga
subprogramoramainprogramweneednotbeconcernedthatnamesusedinoneprogramunit
mightclashwiththoseinanotherprogramunit.Thisisonereasonwhyitthenbecomespossible
towritelibrariesofusefulsubprograms,functionsandsubroutines,whichcansubsequentlybe
usedinotherprogramsofyoursorotherpeople's.
Notethatitispossibletohavearraynamesassubroutineargumentsthearrayorarraysmustbe
declaredwithinthebodyofthesubroutineaswellasinthecallingroutine.However,unlikeinamain
program,wherethedimensionsofanarraymustbedeclaredoffixedsize,anarraydeclarationwithin
asubroutinemayspecifythenameofavariableinthedeclaration.
Forexample,hereisafragmentofaprogramwhichcallsasubroutinetotakeavectorof'number'
dataevents(uptoamaximumof150)andreturnacharacterarrayofsize70x'number'whichcan
thenbeprintedtogiveacrudehistogram
programanalys
implicitnone
integernumber
realevents(150),xmin,xmax
character*1matrix(70,150)
:
:
callhist(xmin,xmax,events,matrix,number)
:
:
stop
end
subroutinehist(xlow,xhigh,dvec,harray,n)
implicitnone
integern
realdvec(n),xlow,xhigh
character*1harray(70,n)
:
:
return
end

http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

28/30

3/14/2015

IntroductiontoFortranProgramming

ClickhereifyouwishtoreturntotheTableofContents.

10.COMMON
{{{OPTIONAL
Subprogramsareusefulinstructuringlargeprogramsintosubtasks,butcommunicationbetweenthe
differentprogrammodulesviaparameterlistsisnotalwaysappropriate.Theremaybeabodyof
variableswhichhavetobeaccessedbymanyofthesubtasksbutdon'treally'belong'toanyofthem.
Fortranallowsustodeclarea"common"blockofvariablesforthispurpose.
NAMEDCOMMONBLOCKS
Anamedblockofstorageisdefinedbythestatement:
common/'name'/'n1','n2',....

where'name'istheglobalnameofthe"common"blockand'n1','n2',...isalistoflocalvariable
names,arraynamesorarraydeclarators.Forexample,
integerage(50),num
realmark(50,6),av,avrage
common/exam/num,mark,av(50),age,avrage

definesa"common"blockcalledexamwhichconsistsof402numericstorageitems.Thefirstofthese
isaninteger,num,thenext300atwodimensionalarraymark,thenext50arealarrayav,thenext50
anintegerarrayageandthelastarealvariableavrage.
*********************************
*Warningoncommonblocknames*
*********************************

Becausethenameofa"common"blockisglobal,itmustbedifferentfromthenamesofanyother
"common"blocksorprogramunits.
Notes:
Ifa"common"blockcontainsanycharactervariablesorcharacterarraysthenitcannotcontain
anyvariablesorarraysofanyothertype.
Thecommonstatementisaspecificationstatementandmustthereforeprecedeanydata
statementsorexecutablestatements.Althoughnotmandatory,itisagoodideatoplaceanytype
orarraydeclarationsofitemsthatappearinthecommonstatementimmediatelybeforeit,asin
theexampleabove.
Becauseonlythenameofa"common"blockisglobal,differentprogramunitsmayrefertothe
individualitemswithinthe"common"blockindifferentways.Forexample,theblockexamin
theaboveexamplemightbedefinedinanotherprogramunitas
common/exam/n,total(50,6),av(50),nyrs(50),avyrs

orevenas
common/exam/n,score(50,7),nage(50),avrage

wherethetworealarrayshavebeendeclaredasasinglerealarray.Becauseoftheruleabout
storageorderinFortran77,thoseelementsofscorewithsecondsubscript7occupythelast50
storagelocationsandthuscorrespondexactlytothearrayavinthefirstspecification.
http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

29/30

3/14/2015

IntroductiontoFortranProgramming

BLANKCOMMON
Aswellasblocksofstorageoffixedsizewithglobalnames,Fortran77allowsustohaveasingle
furtherblockofstoragethatisavailabletoanyprogramunitandthathasneitheranameorafixed
size.Thisisknownas"blankcommon"andisdeclaredthus:
common'n1','n2',.....

where'n1','n2',...isalistoflocalvariablenames,arraynamesorarraydeclarators.Forexample,
commonx,y,a(10:10)

Notes:
Unlikenamed"common"blocks,thesizeofblank"common"neednotbethesameindifferent
programunits.
Blank"common"isusuallymoreappropriatewhereseveralvariablesand/orarraysaretobe
madeavailabletoall(ornearlyall)programunits.
}}}
ClickhereifyouwishtoreturntotheTableofContents.

http://www2.ph.ed.ac.uk/~playfer/f77_tut.html

30/30

Вам также может понравиться