Copyright©JanetANicholson2011 1 fortrantutorial.com IntroductiontoProgramming usingFORTRAN95 http://www.fortrantutorial.com/ Theseworksheetsaimtoprovideanintroductionto programming.ThelanguagechosenforthisisFORTRAN95.This isbecauseFORTRANisparticularlysuitableforscienceand engineering;itisalsoverywidelyavailable. Theskillsyouacquireworkingthroughthesenotescanbe appliedtoanycomputinglanguage.Theconceptsyouwilllearn aresharedincommonwitheveryothercomputinglanguage. Thisdocumentandalltheexamplesmaybefoundonlineat: http://www.fortrantutorial.com/ ©JanetANicholson2011 Copyright©JanetANicholson2011 2 fortrantutorial.com 1 THEBASICS 3 1.1 AIMS 3 1.2 INSTALLFTN95PERSONALEDITION 3 1.3 YOURFIRSTPROGRAMMINGSESSION 3 1.4 PLATOAPROGRAMMINGE NVIRONMENT 3 1.5 RUNNINGYOURFIRSTFORTRAN95PROGRAM 4 1.6 PROGRAMSTRUCTURE 6 1.7 MOREONINPUTANDOUTPUT 6 1.8 MOREDATATYPES–INTEGERANDCHARACTER 8 1.9 SAVINGTHECONTENTSOFOUTPUTWINDOW 10 2 MAKINGDECISIONS 11 2.1 AIMS 11 2.2 ASSIGNMENT 11 2.3 ARITHMETIC 11 2.4 INTRINSICFUNCTIONS 12 2.5 MAKINGDECISIONS 13 2.6 PROGRAMSTYLE 14 2.7 MOREONDECISIONMAKING 14 2.8 OTHERLOGICALOPERATORS 14 2.9 MULTIPLECONDITIONS 15 2.10 THESIMPLEIFSTATEMENT 15 2.11 IMPORTANTNOTE–TESTINGFORZERO 16 3 LOOPS 17 3.1 AIMS 17 3.2 MIXINGVARIABLETYPES 17 3.3 THEDOLOOP 18 3.4 NESTEDDOLOOPS 19 3.5 USINGLOOPSTODOSUMMATION 20 4 USINGFILESANDEXTENDINGPRECISION 22 4.1 AIMS 22 4.2 READINGFROMFILES 22 4.3 WRITINGTOFILES 23 4.4 EXTENDINGTHEPRECISION 23 4.5 MAGNITUDELIMITATIONS 25 4.6 CONVERGENCE–EXITINGLOOPSONACONDITION 25 5 ARRAYSANDFORMATTEDI/O 27 5.1 AIMS 27 5.2 ARRAYS 2 7 5.3 ARRAYMAGIC 29 5.4 MULTIDIMENSIONALARRAYS 30 5.5 FORMATTINGYOUROUTPUT 31 5.5.1 IntegerSpecification 32 5.5.2 FloatingpointSpecification 32 5.5.3 ExponentialSpecification 32 5.5.4 CharacterSpecification 33 5.6 IMPLIEDDOLOOPTOWRITEARRAYS 33 6 SUBROUTINESANDFUNCTIONS 35 6.1 AIMS 35 6.2 REUSINGCODE–THESUBROUTINE 35 6.3 ARGUMENTSTOSUBROUTINES 36 6.4 USERDEFINEDFUNCTIONS 38 7 ADVANCEDTOPICS 40 7.1 AIMS 40 7.2 ARRAYFUNCTIONS 40 7.3 WRITINGREALPROGRAMSFLOWCHARTS 42 Copyright©JanetANicholson2011 3 fortrantutorial.com 1 TheBasics 1.1 Aims Bytheendofthisworksheet,youwillbeableto: CreateandrunaFORTRAN95program Understandbasicprogramstructure Starttodealwithprogrammingerrors Starttounderstandreal,integerandcharactervariabletypes. SaveacopyofyouroutputinWord. 1.2 InstallFTN95PersonalEdition SearchforSilverfrostFTN5personaleditionorclickthislink http://www.silverfrost.com/32/ftn95/ftn95_personal_edition.aspx . Downloadandinstallthesoftwareacceptingallthedefaults. 1.3 Yourfirstprogrammingsession LocateanddoubleclickthePlato icon ClickFile,New SelectFreeFormatFortranFile ClickFile,SaveAs Createadirectorycalledfortranprogramsandopenit Typefirst.f95 1.4 Platoaprogrammingenvironment Copyright©JanetANicholson2011 4 fortrantutorial.com Platoisa"programmingenvironment".WithinPlato,youcancreateandeditprogramsandgetthem torun.Plato'seditorisspecial–itunderstandsthesyntaxofvariousprogramminglanguages.Wetell Platowhichlanguageweareusingwhenwecreateouremptyfileandsaveitwitha.f95(FO RTRAN 95)extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable tocheckthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsaboutusinga colourcodetodistinguishbetweenthevariouselementsofthelanguage. Alwaysensurethatyourprogramfileshavea.f95extension 1.5 RunningyourfirstFORTRAN95Program Exercise1.1 Typeinthefollowingexactlyasshown: !My first program program first print *,'This is my first program' end program first Copyright©JanetANicholson2011 5 fortrantutorial.com Clicktheblack,(theExecutebutton). PlatowillgetFTN95tocheckyourprogramforerrors.Ifitfindsanyproblems,itwillgiveyou thedetails.Ifyouhavetypedintheprogramexactlyasshownabove,anexecutablefilewill begenerated(first.exe).Platowillthenautomaticallygetthepro gramtostartexecuting. Abannerwillappearforacoupleofsecondsandwillthendisappear(that"sthepricewe havetopayforusingthefreesoftware) Ablackconsolewindowwillappear. PressReturntoclosethewindow.DonotclicktheXatthetopri ghtofthewindow. PlatocangetupsetifyoudonotpressReturntoclosethewindow,trythis… Saveyourprogramfirst! Runtheprogramagain(click) ThistimeclicktheXatthetoprightofthewindowtoclos eit. Makeupyourownmindaboutwhichisthebetterwaytoclosethiswindowinfuture! Copyright©JanetANicholson2011 6 fortrantutorial.com 1.6 ProgramStructure Examinethefollowingshortprogram: program sum !a:nameofprogram !an example of program structure !b:acomment real :: answer,x,y !c:declarations print *, 'Enter two numbers' !d:output read *, x !e:input read *, y !e:input answer=x+y !f:arithmetic print *, 'The total is ', answer !g:output end program sum !h:endofprogram Thereareanumberofgeneralpointshere: Theprogramismadeupofanumberoflines.Eachlineiscalledastatement. Eachstatementismadeupof variablenamese.g.answer, x, y operatorse.g.+,-etc keywordse.g.read, print Thestatementsareexecutedsequentially. Let'sbreaktheprogramdown,linebyline: a) Thenameoftheprogram.Keepitreasonablyshortandmeaningful. b) Acommentexplainingthepurposeoftheprogram.Commentsareindicatedbyan exclamationmark.Alltexttotherightofanexclamationmarkisignoredbyth ecompiler. Programmersusecommentstohelpthemrememberhowaprogramworks.Useof appropriatecommentsinprogramsaidsunderstandingandisgoodpractice. c) Variablesanswer, x and y areusedtostorefloatingpointnumbers–weindicate thisbydeclaringthemasreal. d) print *,outputstoth escreen–theasteriskmeansusethedefaultnumberofdecimal placeswhenthenumberiswrittentothescreen. e) Wereadinformationfromthek eyboardandstorethevaluesin xandy. f) Dosomearithmeticandstoretheanswerinanswer. g) Outputtheresulttoth escreen h) Concludetheprogram 1.7 MoreonInputandOutput Exercise1.2 Openanewfileandcallitio.f95. Typeinthefollowingprogram: program io real :: x,y,z print *, 'enter the values x,y and z' read *, x,y,z print *, 'the values you typed are for z,y,x are: ',z,y,x end program io Executeitbypressing YoucanenterthenumbersoneatatimeandpresstheEnterkeyeachtime. Executetheprogramagain Thistimetypeallthreenumbersononelineseparatedbycommas. Copyright©JanetANicholson2011 7 fortrantutorial.com Lookattheprintstatement print *, 'the values you typed are for z,y,x are: ',z,y,x Inthisstatement,weareoutputtingfourseparatethings,aliteralstringofcharacters, 'the values you typed are for z,y,x are: ' andthevariablesz,y,andx.Wemayoutputseveralitemsatonetime,providedtheyareseparated bycommas. Exercise1.3 Thefollowingprogramhasanumberoferrors. Createanewfilecalledbug.f95andthentypeinthefollowingprogramexactlyasshown. Youcanalsodownloadthisfilefrom http://fortrantutorial.com/fortrantutorialexampleprograms/index.php program bug this program is full of errors real :: a,b,c a = b + c read *,c print *,a end program simple Thecompilerwillreporttwoerrormessageswhenitattemptstocompile.Clickonthedetailsbutton. Eacherrorgeneratesamessage. Doubleclickingonthemessagewill takeyoutothelineintheprogramwherethefaultoccurs. Copyright©JanetANicholson2011 8 fortrantutorial.com Correctthetwoerrors. ClickExecute Thereisnowonefurthererror,Platowillprovideayellowwarningalert.Watchthescreen carefully!Thewindowwillcloseandthentheprogramwillstarttoexecute.Somethingis notcorrecthowever…theprogramwill"hang".Itisactuallywaitingforyoutoinputavalue, becauseoftheline read*,c.Totheuseroftheprogram,thisisnotatallobvious–they mayhavethoughtthattheprogramhascrashed! Typeinanumberthenpressenter Theprogramreturnsanstrangevalue.Thisisan"executiontime"error. Weneedtofindoutwhatthewarningmessagewas.Clickthe"compile"button(totheright ofthebinoculars).Thenclickthe"details"button.Platowilltellyouthatthevariablebhas notbeengivenavalue. Correcttheprogramtogivebavalue,andthenexecutetheprogramagain. Thereisstillaproblem.Thistime,itisaproblemwiththeprogram'slogic. NeedaHint?Theprogramstatementsareexecutedsequentially. a=b+c read *, c print *, a Thestatementa=b+cdoesn'tmakesense,asatthisstageoftheprogram,wehaven'tyetgivena valuetoc. Importantpointstonote Therearetwotypesoferrorsassociatedwiththisprogram:compilererrorsandruntime errors. Theprogramisalsouserunfriendly.Theprogramwaitsforinputwithouttellingtheuser whatisneeded. Fixtheruntimeerrorby: readinavalueforb correcttheorderofthestatements maketheprogrammoreuserfriendly, thencompareyourprogramwiththeonecalledbu gfixed.f95at http://fortrantutorial.com/fortrantutorialexampleprograms/ 1.8 MoreDatatypes–integerandcharacter Sofar,wehaveonlyusedreal(floatingpointnumbers)inourprograms.Wecanalsospecifythat numbersareintegerandcharacter.Programconvert,below,demonstratestheiruse. Withinagivenrange,integersarealwaysrepresentedexactlywhereastheprecisionofrealnumbers islimitedbythearchitectureofthemachine.Therealvariabletypegivesus6figurede cimal precision.(Ifthisdoesn'tseemenough–don'tworrywe'llcomebacklateronwhenweexaminehow toincreasethenumberofdigitsofprecisioninSection4). Charactervariablesholdstringsofcharacterslike 'A happy day was had by all' 'Yes' 'N' '3 + 4 equals 7' Copyright©JanetANicholson2011 9 fortrantutorial.com Whenthecharactervariableisdeclared,weshowthemaximumlengththatthestringcanoccupyby followingthenamebya*thenitsmaximumlength.Theexamplebelowhasamaximumlengthof10 charactersallowedforaperson'sname–thismightnotalwaysbeenough!Youhavetomakea judgementher e. program convert !This example shows the use of integer and character variables. implicit none integer :: pounds,pence,total character :: name*10 print *,'What is your name?' read *,name print *, 'Hi ',name,'! Enter number of pounds and pence' read *, pounds,pence total =100 * pounds + pence print *,'the total money in pence is ',total end program convert NOTEtheinclusionoftheline implicit none Byincludingitinyourprogram,FORTRANwillcheckthatyouhaveproperlydeclaredallyourvariable types.Inthebadolddaysofprogramming,declarationofvariableswasthoughttobeunnecessary andtheoldFORTRANcompilersusedanimplicitconventionthatintegershavenamesstartingwith thelettersinth erangei–n,alltheothersbeingreal.FORTRANstillallowsyoutodothisifwedon't includetheline,implicitnone.Timehasshownthatoneofthecommonestreasonsforerrorina programistheincorrectuseofvariables. Alwaysuseimplicitno neatthestartofeveryprogram. Exercise1.4 Withtheprogramconvertinsection1.5asaguide,writeaprogramtotestouteverythingyou've learnedsofar.Youmightincludedifferenttypesofvariables,forexamplereal,integer,and character.Includeinputandoutputusingreadandprint.Anexamplemightbeaprogramthatasks peoplequestio ns,includingthingsliketheirageandnameandsoon.Itcould,forexample,printout theiryearofbirthwithasuitablemessage.It'suptoyou,justuseyourimagination. Copyright©JanetANicholson2011 10 fortrantutorial.com 1.9 SavingthecontentsofOutputWindow Runyourlastprogramagain.Whentheblackoutputwindowopensrightclickonthe Platoiconinthetopleftcorner Clickonedit ClickSelectall Clickcopy OpenanewdocumentinWordorNotepadandclickpaste. [...]... able to: Do arithmetic Start to use FORTRAN intrinsic functions Begin to understand program flow and logic Know how to test for zero – important! Learn more about good programming style 2.2 Assignment When we start programming, the similarity between mathematical equations and FORTRAN statements can be confusing Consider the following FORTRAN statements: Store the value 2 in memory location x Store... result Hint you need to declare a third variable for intermediate storage of the data (Check your program by examining program swap.f95 at http://fortrantutorial.com/fortrantutorial example programs/ 2.3 Arithmetic The arithmetic operators are +,plus and minus *,/ multiply and divide ** exponentiation (raise to the power) () brackets The order of precedence in FORTRAN is identical to that of mathematics... Nicholson 2011 17 fortrantutorial.com To get over this problem, we have to signal to FORTRAN that we want it to calculate the right hand side of the expression using real arithmetic If we want to keep x as integer data type, we could re write our expression as follows: y=x/3.0 The presence of a real number on the right hand side causes the right hand side of the expression to be evaluated using floating... typing and is prone to error Imagine if we had to deal with thousands of numbers! The way around this is to use arrays An array is a list that we can access through a subscript To indicate to FORTRAN that we are using an array, we just specify its size when we declare it real, dimension(100) ::x x(1) = 3 x(66) = 4 This snippet of code allocates 100 memory locations to the array x To access an individual... program twodra Copyright © Janet A Nicholson 2011 30 fortrantutorial.com FORTRAN actually allows the use of arrays of up to 7 dimensions, a feature which is rarely needed To specify a extended precision 3 dimensional array b with subscripts ranging from 1 to 10, 1 to 20 and 1 to 30 we would write: real (kind=ikind),dimension(10,20,30) :: b Exercise 5.4 Using a 4*4 array create an identity matrix, that... want to construct a table of values for z where z = xy for values of x in the range 1 to 2 in steps of 0.5 and y in the range 1 to 2 in steps of 0.5 Work through the next exercise which illustrates this: Copyright © Janet A Nicholson 2011 19 fortrantutorial.com Exercise 3.5 Copy program xytab.f95 to your filespace program xytab implicit none !constructs a table of z=x/y for values of x from 1 to 2... yourself and think carefully about its implications This program demonstrates how easy it is to get calculations wrong I’ll leave this to you to experiment to ensure that you fully understand the importance of properly declaring variables and the use of constants in FORTRAN programming A systematic approach to your programming will reduce the risk of errors as will running programs with test data that have... 2011 16 fortrantutorial.com 3 Loops 3.1 Aims By the end of this worksheet, you will be able to: Understand more about the use of real and integer variables and how to use a mixture of data types in expressions Understand how to re use code by looping Know how to control the number of times a section of code is executed by using a do loop 3.2 Mixing variable types Exercise 3.1 Copy divide.f95 Make sure... allocatable,dimension(:):: vector !note syntax - dimension(:) integer :: elements,i print *,'enter the number of elements in the vector' read *,elements allocate(vector(elements)) !allocates the correct amount of memory print *,' your vector is of size ',elements,' Now enter each element' do i=1,elements read *,vector(i) end do print *,'This is your vector' do i=1,elements print *,vector(i) end do deallocate(vector) !tidies... conditions end if 2.8 Other logical operators So far, all our tests have been for equality There are several tests we can make: == /= < >= equal to (there is no space between the equals signs) not equal to less than less than or equal to greater than greater than or equal to Copyright © Janet A Nicholson 2011 14 fortrantutorial.com 2.9 Multiple Conditions Suppose we need to test if x is greater than y and . Copyright©JanetANicholson2011 1 fortrantutorial.com Introduction to Programming using FORTRAN 95 http://www.fortrantutorial.com/ Theseworksheetsaim to provideanintroduction to programming. Thelanguagechosenforthisis FORTRAN 95. This isbecause FORTRAN isparticularlysuitableforscienceand engineering;itisalsoverywidelyavailable. Theskillsyouacquireworkingthroughthesenotescanbe applied to anycomputinglanguage.Theconceptsyouwilllearn aresharedincommonwitheveryothercomputinglanguage. Thisdocumentandalltheexamplesmaybefoundonlineat: http://www.fortrantutorial.com/ ©JanetANicholson2011 Copyright©JanetANicholson2011. Canyouseewhatishappening? FORTRAN iskeepingth eintegerpartoftheanswerandthrowingthe restaway. Makesureyouunderstandthis thoroughly! Copyright©JanetANicholson2011 18 fortrantutorial.com To getoverthisproblem,wehave to signal to FORTRAN thatwewantit to calculatetherighthand sideoftheexpression using realarithmetic.Ifwewant to keepxasintegerdatatype,wecouldre writeourexpressionasfollows: . Typefirst.f95 1.4 Platoa programming environment Copyright©JanetANicholson2011 4 fortrantutorial.com Platoisa" ;programming environment".WithinPlato,youcancreateandeditprogramsandgetthem to run.Plato'seditorisspecial–itunderstandsthesyntaxofvarious programming languages.Wetell Platowhichlanguageweare using whenwecreateouremptyfileandsaveitwitha.f95(FO RTRAN 95) extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable to checkthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsabout using a colourcode to distinguishbetweenthevariouselementsofthelanguage. Alwaysensurethatyourprogramfileshavea.f95extension 1.5