Sunteți pe pagina 1din 8

FORTRAN HANDBOOK

Created by Tyler Brannan


1|C S C 1 1 2

Lab1: FORTRANBasicsReading,Writing,andArithmetic
gedit and gfortran
CSC112usesatexteditornamedgedittowriteFORTRANprograms.Welaunchtheeditorwith thefollowingcommand: eos% gedit & Programsshouldbesavedasname.f95,wherenamecanbechangedtotheprogrammers specifications. Weusethecompilergfortran.Oncewehavewrittenaprogramingedit,thenitmustbe compiledintoanexecutablecontainingonly0sand1ssothattheterminalcanrunit.The syntaxforcompilingis: eos% gfortran name.f95 Thislinecreatesanexecutablenameda.outifourprogramcompiles.Weknowourprogram hascompiledcorrectlyiftherearenoerrormessagesprintedtotheterminal.Ifwehave successfullycompiledourcode,thenwecanrunourexecutableasso: eos% ./a.out Ifnot,fixyourerrorsingeditandretrycompiling.Weencourageyoutocompileoften;itsfree andeasy!Whenyouhavethefinalversionofyourprogram,runthefollowingcommand: eos% mv a.out name.exe Itwillchangethenameofyourexecutabletoname.exewherenameischangedtohelpeasily identifytheprogram.

2|C S C 1 1 2

Essentials
Everyprogramyouwritethissemesterwillcontainthefollowingthreelinesofcode: PROGRAM pname IMPLICIT NONE END PROGRAM pname PROGRAM and END PROGRAM simplyletthecompilerknowtheboundariesofyourprogram withpnamebeingthenameyoucanchooseforyourprogram.Programnameshaveafew rules: 1. Mustbe<32characters 2. Startwithaletter 3. Onlycontainletters,numbers,andunderscores 4. NoSpaces!firstprogramisnotvalidbutfirst_programis IMPLICIT NONE makesaprogrammerdeclareallvariablesused,andwerequireour studentstohavethisineveryprogram.Allofourcodetherestofthesemester,untilLab7, goesinbetween IMPLICIT NONE and END PROGRAM.Iwanttoaddinherewhyweuse implicitnone. Afterthe IMPLICIT NONE, weplaceourvariabledeclarations.Avariableisusedtostore information.If,forinstance,wewantedtousethenumber5severalplacesinourprogram, thenweshouldstoreitinavariable,thatwecouldchoosetocallx.Throughouttherestofour programunlesswechangethevalue,theprogramrecognizesxasrepresenting5.Variable nameshavethesamerulesasprogramnameslistedabove.Therearefourtypesofvariable thatweuseinthiscourse,withexamplesofpossiblevaluesstoredinsidethesevariablesin parentheses: 1. INTEGER(4,0,7) 2. REAL(6.9,4.000,5.) 3. CHARACTER(hi,8,a) 4. LOGICAL(.TRUE.,.FALSE.) INTEGERvariablesmayonlystorenumberswithoutdecimals.REALvariablesareusedtostore numberswithdecimalsevenoneslike5.whichisthesameas5.0;ifyoutrytostorethe INTEGER5inaREALvariablethenitisautomaticallypromotedtoaREALnumber. CHARACTERvariablesmaystoreanythingaslongaswhatisstoredisnotlongerthanthe specifiedlengthofthevariable,discussedbelow.LOGICALvariablesstoreonly.TRUE.or .FALSE.

3|C S C 1 1 2

Nowhowdowedeclareandwhatdoesthatmean?Wemustdeclareavariableinorderforthe programtoknowthatitisavariableandthereforecanhaveinfostoredintoit.LOGICAL, INTEGERandREALvariablesarealldeclaredwiththesamesyntax: REAL:: var1, var2 INTEGER:: variable LOGICAL::v Noticethatwefirststatewhatvariabletypewearedeclaringfollowedbytwocolons,thenwe givethenamesofthevariablesseparatedbycommas.However,forCHARACTERvariables,we muststatehowmanycharactersareallowedtobestoredinthevariable: CHARACTER(5)::choice,answer Thepreviouslineofcodecreatestwovariablesthatcanstorestringslikehelloorhibutnot howdie.Ifyoudonotspecifythelengthofthevariable,thenitdefaultstoone,andifyoutry tostoreyes,yisstoredinthevariable. NoticethatCHARACTERstrings,whicharewhatwestoreinCHARACTERvariables,are surroundedbysinglequotes.Thequotationshelpustodistinguishbetweenastringof charactersandavariablename. Hereisanexampleofthat: class = "mathematics" ThisstatementssimplymeansthatIhavetoldthecomputertostorethecharacterSTRING mathematicsinsidethecharacterVARIABLEclass


4|C S C 1 1 2

WRITE and READ


Now,weneedtolearnhowtosendoutputtoandreceiveinputfromtheterminal.Thesyntax foroutputis: WRITE(*,*) <What we want to write> Nowthat'salittlebland,solet'slookatanexamplethatdescribescharacterstrings,variables, andevensomemath: WRITE(*,*) Name: , first_name, Age: , lie+5 Thereareseveralimportantthingsofwhichtotakenotefromthepreviouslineofcode. First,letsgooverthe*,* Thefirst*denoteswhatiscalledtheUNITNUMBER.ThetellsFORTRANwheretosendthe output.WellmanipulateandlearnaboutthisconceptintheFILEI/Olab,butfornowjust knowthatthe*meansstandardoutputinaWRITEstatement,andstandardinputinaREAD statement. Thesecond*controlsFORMATTING,whichwewilllearnallaboutintheFORMATTINGlab. However,inthiscontext,the*meansstandardformatting. Second,somepartsofourWRITEstatementaresurroundedbyquoteswhileothersarenot. Anythingwewantwrittentothescreenasiswillbeputintoquotations.Anythingoutsidethe quoteswillbeinterpretedaseitheravariable,first_name,oramathematicaloperation,lie+5, andtheinformationstoredinthevariableorcalculatedwillbewrittentoterminal. Finally,noticethatweseparatedifferentpartsoftheWRITEstatementwithcommas.Asan example,thefollowingwouldshowintheterminalifthecharactervariablefirst_nameheldthe characterstringTylerandthenumber18wasstoredintheintegervariablelie: Name:TylerAge:23 READstatementswillbeusedtoreceivetheusersinputfromtheterminal.Ifwehavethe followinglineofcodeinourprogram,thentheprogramwillhaltandwaitforuserinput: READ(*,*) name, age However,itisimportanttoalwayshaveaWRITEinfrontoftheREADsothattheuserknows whatkindofinputisexpected.Soourcodeshouldlooklikethis: WRITE(*,*) What is your name and age?
5|C S C 1 1 2

READ(*,*) name, age Notice,wemayreadmorethanonethingintovariablesatatime.Inordertoseparatethetwo inputswhenenteringthemontheterminal,thentheusershouldeitherseparatetheinputwith aspaceoracommalikeso: Tyler22 OR Tyler,22

Itisimportantthattheinputmatchesthevariabletype.SoifnameisaCHARACTERvariable andageanINTEGER,R2D2willworkastypedinputfornamebecausenumbersandlettersare characters,butagelessdoesnotworkforageandwillcreateanerrorendingyourprogram.

Arithmetic
ArithmeticinFORTRANcanbetrickytobeginnersifyoudonotknowcertainrules.Thefirst issuewemusttackleinthissectionistheequalsign.Itcanbeasourceofconfusionfor beginningprogrammers.Ifyouseex=x+1incode,youmaythinkwaitthatmeans0=1whichis falsesowehaveanerror!However,inFORTRANtheequalssignmeansassignment. ForINTEGERandREALvariables,ourprogramwillcalculateanumberontherightsideofthe equalssignandstoreitinsidethevariableontheleft.Thatmeansthatx+1=xisinvalid,but x=x+1willaddonetothepreviousvalueofx.ForCHARACTERvariables,wesimplyputsome characterstringdesignatedbyquotesontherightsideanditisstoredintothecharacter variableontheleftlikeso: name = Tyler Also,whathappensifwehavethefollowing3linesofcodeinaprogram? CHARACTER(3)::word word= Books WRITE(*,*) word Thefollowingwillbewrittentotheterminalbecausethevariableisonlyoflength3: Boo Somakesureyousetyourlengthswisely! Now,wecanactuallylearnsimplemath.Thereare5operationswewilluse,andyoushould useparenthesesaroundoperationstomakesurethemathyouexpectisbeingdone.
6|C S C 1 1 2

Operation Commonsymbol FORTRANsymbol Addition + + Subtraction Multiplication x * Division / Exponentiation ^ ** Notice,FORTRANwillnotunderstand(x^2)butwill(x**2)sobecareful.Anotherpointthat mustbeclarifiedoryoucouldgetstrangeanswersisthedifferencebetweenREALandINTEGER division.Whatdoyouthinktheanswerto5/2isinFORTRAN?Theansweris2!Thisstrange solutionisduetothefactthatwedividedtwointegers. AnytimewedividetwointegersFORTRANtakestheactualanswer2.5andthrowsawaythe decimalplacesendingupwithanINTEGER2.ThesolutionifwewantedaREALansweristo makesureournumbersareREALlike5.0/2.0;donotmixINTEGERandREALifpossible.One possibleexceptionissometimeswewanttopromoteanINTEGERtoaREAL(make8tobe8.0) whichcanbedonewith: REAL_variable=INTEGER_variable

Miscellaneous
Variablesmaybeinitializedwhendeclared;thatmeanssimplygivingavalueatthesamewe declareitlikethis: LOGICAL:: duh=.TRUE. CHARACTER(5):: me=Tyler Also,wemaysetavariableasaPARAMETER.Thatmeansthevariablehasapermanentvalue whichmaynotbechangedintheprogramwhendeclaredlikeso: REAL,PARAMETER:: pi=3.14, e=2.72 INTEGER,PARAMETER:: x=10 Donottrytodomathwithcharacters.Evenif5and6arestoredinCHARACTERvariablesaand brespectively,youcannotadda+b. AnintrinsicfunctionissomethingthatisbuiltintoFORTRAN,andyoucancallitatwhichtimeit returnssomethingbacktotheprogram. Forinstance,ifwehave answer=SIN(x), thenthesineofxisstoredintoanswer. However,youcannothaveafunctionbyitselfonaline;itwouldbethesameasjusttypingthe number4onaline.Notonlywoulditnotmakesense,itcausesanerror.

7|C S C 1 1 2

Commonintrinsicfunctionsaretrigfunctions,ABS(x)whichreturnsabsolutevalue,and SQRT(x)whichreturnsthesquareroot. AnextremelyvaluableassetofFORTRANistheabilitytoplacecommentsinourcodewhichthe compilerwillignorewhenlookingforerrors.Commentsarepurelyforsomeoneviewingcode. Thereareusedtoclarifypartsofcodethatmaybeconfusingoraddinggeneralinformation abouttheprogram.Youarerequiredtoputyourname,labsection,andwhichlab assignmentyouarewritingintheformofcommentsineachprogram. Commentsaredonebysimplyplacinganexclamationmarkinfrontofanythingtobe commentedout: !Name: Tyler Brannan !Section: 222 Assignment: Lab 1 part3.f95 FORTRANISNOTcasesensitive;theterminalIScasesensitive.Submit.f95filesNOT executablesandnameyourprogramfilespart1.f95,part2.f95,andpart3.f95respectively.

8|C S C 1 1 2

S-ar putea să vă placă și