O O P bject riented rogramming F via ortran 90/95 Ed Akin RiceUniversity MechanicalEngineeringand MaterialsScience Department Houston,Texas May29,2001 Draft#4.2, Copyright c2001, Allrightsreserved. (cid:13) ii Contents Preface vii 1 ProgramDesign 1 1.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2. ProblemDefinition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3. ModularProgramDesign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4. ProgramComposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4.1. Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4.2. Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4.3. FlowControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.4.4. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.4.5. Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.4.6. DynamicMemoryManagement . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.5. Programevaluationandtesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.6. Programdocumentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.7. ObjectOrientedFormulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.8. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2 DataTypes 23 2.1. IntrinsicTypes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.2. UserDefinedDataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.3. AbstractDataTypes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.4. Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.5. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3 ObjectOrientedProgrammingConcepts 33 3.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.2. Encapsulation,Inheritance,andPolymorphism . . . . . . . . . . . . . . . . . . . . . 34 3.2.1. ExampleDate,Person,andStudentClasses . . . . . . . . . . . . . . . . . . . 37 3.3. ObjectOrientedNumericalCalculations . . . . . . . . . . . . . . . . . . . . . . . . . 38 3.3.1. ARationalNumberClassandOperatorOverloading . . . . . . . . . . . . . . 39 3.4. Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 3.5. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4 FeaturesofProgrammingLanguages 51 4.1. Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.2. StatementsandExpressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.3. FlowControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.3.1. ExplicitLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.3.2. ImpliedLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.3.3. Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.4. Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 c2001 J.E. Akin iii (cid:13) 4.4.1. FunctionsandSubroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.4.2. GlobalVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.4.3. BitFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 4.4.4. ExceptionControls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 4.5. InterfacePrototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 4.6. CharactersandStrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 4.7. UserDefinedDataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 4.7.1. OverloadingOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 4.7.2. UserDefinedOperators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.8. PointersandTargets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.8.1. PointerTypeDeclaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 4.8.2. PointerAssignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.8.3. UsingPointersinExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.8.4. PointersandLinkedLists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.9. AccessingExternalSourceFilesandFunctions . . . . . . . . . . . . . . . . . . . . . 89 4.10.ProceduralApplications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.10.1. FittingCurvestoData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.10.2. Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 4.11.Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5 ObjectOrientedMethods 103 5.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 5.2. TheDrillClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 5.3. GlobalPositioningSatelliteDistances . . . . . . . . . . . . . . . . . . . . . . . . . . 106 5.4. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 6 InheritanceandPolymorphism 119 6.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 6.2. ExampleApplicationsofInheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 6.2.1. TheProfessorClass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 6.2.2. TheEmployeeandManagerClasses . . . . . . . . . . . . . . . . . . . . . . . 121 6.3. Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 6.3.1. Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 6.3.2. SubtypingObjects(DynamicDispatching) . . . . . . . . . . . . . . . . . . . 130 6.4. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7 OODataStructures 135 7.1. DataStructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 7.2. Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 7.3. Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 7.4. LinkedLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 7.4.1. SinglyLinkedLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 7.4.2. DoublyLinkedLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 7.5. Direct(Random)AccessFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 7.6. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 8 ArraysandMatrices 155 8.1. SubscriptedVariables:Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 8.1.1. InitializingArrayElements. . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 8.1.2. IntrinsicArrayFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 8.1.3. ColonOperationsonArrays(SubscriptTriplet) . . . . . . . . . . . . . . . . . 159 8.1.4. ArrayLogicalMaskOperators . . . . . . . . . . . . . . . . . . . . . . . . . . 163 8.1.5. UserDefinedOperators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 8.1.6. ConnectivityListsandVectorSubscripts . . . . . . . . . . . . . . . . . . . . 166 c2001 J.E. Akin iv (cid:13) 8.1.7. ComponentGatherandScatter . . . . . . . . . . . . . . . . . . . . . . . . . . 168 8.2. Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 8.2.1. MatrixAlgebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 8.2.2. Inversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 8.2.3. Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 8.2.4. DeterminantofaMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 8.2.5. MatrixCalculus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 8.2.6. ComputationwithMatrices . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 8.3. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 9 AdvancedTopics 181 9.1. Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 9.2. SubtypingObjects(DynamicDispatching) . . . . . . . . . . . . . . . . . . . . . . . . 183 9.3. Non-standardFeatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 A Bibliography 187 B Fortran90Overview 191 B.1. ListofLanguageTables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 B.2. AlphabeticalTableofFortran90IntrinsicRoutines . . . . . . . . . . . . . . . . . . . 17 B.3. SyntaxofFortran90Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 C SelectedExerciseSolutions 47 C.1. Problem1.8.1: Checkingtrigonometricidentities . . . . . . . . . . . . . . . . . . . 47 C.2. Problem1.8.2: Newton-Raphsonalgorithm . . . . . . . . . . . . . . . . . . . . . . 47 C.3. Problem1.8.3: Gameoflife . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 C.4. Problem2.5.1: Conversionfactors . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 C.5. Problem3.5.3: Creatingavectorclass . . . . . . . . . . . . . . . . . . . . . . . . . 50 C.6. Problem3.5.4: Creatingasparsevectorclass . . . . . . . . . . . . . . . . . . . . . 56 C.7. Problem4.11.1: Countthelinesinanexternalfile . . . . . . . . . . . . . . . . . . . 61 C.8. Problem4.11.3: ComputingCPUtimeuseage . . . . . . . . . . . . . . . . . . . . . 62 C.9. Problem4.11.4: Convertingastringtouppercase . . . . . . . . . . . . . . . . . . . 62 C.10.Problem4.11.8: Readtwovaluesfromeachlineofanexternalfile . . . . . . . . . . 63 C.11.Problem4.11.14: Twolineleastsquarefits . . . . . . . . . . . . . . . . . . . . . . . 63 C.12.Problem4.11.15: Findthenextavailablefileunit . . . . . . . . . . . . . . . . . . . 65 C.13.Problem5.4.4: Polymorphicinterfacefortheclass‘Position Angle’ . . . . . . . . . 66 C.14.Problem6.4.1: Usingafunctionwiththesamenameintwoclasses . . . . . . . . . . 67 C.15.Problem6.4.3: Revisingtheemployee-managerclasses . . . . . . . . . . . . . . . . 67 D CompanionC++Examples 69 D.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 E GlossaryofObjectOrientedTerms 77 F SubjectIndex 0 G ProgramIndex 1 c2001 J.E. Akin v (cid:13) vi Preface Therehasbeenanexplosionofinterestin,andbooksonobject-orientedprogramming(OOP).Whyhave yetanotherbookonthesubject? Inthepastabasiceducationwassaidtomasterthethreer’s: reading, ’riting,and’rithmetic.Todayasoundeducationinengineeringprogrammingleadstoproducingcodethat satisfy the four r’s: readability, reusability, reliability, and really-efficient. While some object-oriented programming languages have some of these abilities Fortran 90/95 offers all of them for engineering applications.ThusthisbookisintendedtotakeadifferenttackbyusingtheFortran90/95languageasits mainOOPtool. With morethanonehundredpureandhybridobject-orientedlanguagesavailable,one mustbeselectiveindecidingwhichonesmerittheeffortoflearningtoutilizethem. Therearemillions ofFortranprogrammers,soitislogicaltopresentthehybridobject-orientedfeaturesofFortran90/95to themtoupdateandexpandtheirprogrammingskills. ThisworkprovidesanintroductiontoFortran90 aswellastoobject-orientedprogrammingconcepts. Evenwiththecurrentrelease(Fortran95)wewill demonstratethatFortranoffersessentiallyallofthetoolsrecommendedforobject-orientedprogramming techniques. It is expected that Fortran 200X will offer additional object-oriented capabilities, such as declaring”extensible” (or virtual) functions. Thus, it is expectedthat the tools learned here will be of valuefarintothefuture. Itiscommonlyagreedthatthetwo decadesold F77 standardforthe languagewas missingseveral usefulandimportantconceptsofcomputersciencethatevolvedandweremadepopularafteritsrelease, but it also had a large number of powerful and useful features. The following F90 standard included a large number of improvements that have often been overlooked by many programmers. It is fully compatiblewithallold F77 standardcode,butitdeclaredseveralfeaturesofthatstandardasobsolete. Thatwasdonetoencourageprogrammerstolearnbettermethods,eventhoughthestandardstillsupports thosenowobsoletelanguageconstructs.TheF90standardscommitteebroughtintothelanguagemostof thebestfeaturesofothermorerecentlanguageslikeAda,C,C++,Eiffel,etc. Thoseadditionsincludedin part: structures,dynamicmemorymanagement,recursion,pointers(references),andabstractdatatypes along with their supporting tools of encapsulation, inheritance, and the overloading of operators and routines.EquallyimportantforthoseinvolvedinnumericalanalysistheF90standardaddedseveralnew featuresforefficientarrayoperationsthatareverysimilartothoseofthepopularMATLAB environment. Mostofthosefeaturesincludeadditionaloptionstoemploylogicalfiltersonarrays.Allofthenewarray featureswereintendedforuseonvectororparallelcomputersandallowprogrammerstoavoidthebad habitofwritingnumerousserialloops. Thecurrentstandard,F95,wentontoaddmorespecificparallel arraytools, provided“pure”routinesforgeneralparalleloperations,simplifiedtheuse ofpointers,and madeafewuserfriendlyrefinementsofsomeF90features. Indeed,atthistimeonecanviewF90/95as theonlycross-platforminternationalstandardlanguageforparallelcomputing. ThusFortrancontinues tobeanimportantprogramminglanguagethatrichlyrewardstheeffortoflearningtotakeadvantageof itspower,clarity,anduserfriendlyness. We beginthatlearningprocessin Chapter 1 with an overviewof generalprogrammingtechniques. Primarilytheolder“procedural”approachisdiscussedthere,butthechapterisclosedwithanoutlineof thenewer“object”approachtoprogramming.Anexperiencedprogrammermaywanttoskipdirectlyto thelastsectionofChapter1whereweoutlinesomeobject-orientedmethods.InChapter2,weintroduce theconceptoftheabstractdatatypesandtheirextensiontoclasses. Chapter3providesafairlydetailed introductiontotheconceptsandterminologyofobject-orientedprogramming.Amuchlargersupporting glossaryisprovidedasanappendix. ForthesakeofcompletenessChapter4introduceslanguagespecificdetailsofthetopicsdiscussedin c2002 J.E. Akin vii (cid:13) thefirstchapter.TheFortran90/95syntaxisusedthere,butinseveralcasescross-referencesaremadeto similarconstructsintheC++languageandtheMATLABenvironment.Whilesomereadersmaywantto skipChapter4,itwillhelpotherslearntheFortran90/95syntaxand/ortoreadrelatedpublicationsthat useC++orMATLAB. AllofthesyntaxofFortran90isalsogiveninanappendix. Since many Fortran applications relate to manipulating arrays or doing numerical matrix analysis, Chapter 5 presents a very detailed coverage of the powerfulintrinsic features Fortran 90 has added to provideformoreefficientoperationswitharrays. Ithasbeendemonstratedintheliteraturethatobject- orientedimplementationsofscientific projectsrequiringintensiveoperationswith arraysexecutemuch faster in Fortran 90 than in C++. Since Fortran 90 was designed for operationson vector and parallel machines that chapter encouragesthe programmerto avoid unneeded serial loops and to replace them withmoreefficientintrinsicarrayfunctions. Readersnotneedingtousenumericalmatrixanalysismay skipChapter5. Chapter6returnstoobject-orientedmethodswithamoredetailedcoverageofusingobject-oriented analysisandobject-orienteddesigntocreateclassesanddemonstrateshowtoimplementthemasanOOP in Fortran 90. Additional Fortran 90 examples of inheritance and polymorphismare given in Chapter 7. Object-orientedprogramsoften requirethe objectsto be stored in some type of “container”or data structure such as a stack or linked-list. Fortran 90 object-oriented examples of typical containers are giveninChapter8.SomespecializedtopicsformoreadvancedusersaregiveninChapter9,sobeginning programmerscouldskipit. Tosummarizethetwooptionalusesofthistext;itisrecommendedthatexperiencedFortranprogram- merswishingtolearntouseOOPcoverChapters2,3,6,7,8,and9,whilepersonsstudyingFortranfor thefirsttimeshouldcoverChapters1,2,3,and.Anyoneneedingtousenumericalmatrixanalysisshould alsoincludeChapter5. AOOglossaryisincludedinanappendixtoaidinreadingthistextandthecurrentliteratureonOOP. Another appendix on Fortran 90 gives an alphabetical listing on its intrinsic routines, a subject based list of them, a detailed syntaxof all the F90 statements, and a set of exampleuses of everystatement. Selected solutionsfor most of the assignments are included in anotherappendixalong with comments on those solutions. The final appendix gives the C++ versions of several of the F90 examples in the text. TheyareprovidedasanaidtounderstandingotherOOPliterature. SinceF90andMATLABareso similarthecorrespondingMATLABversionsoftendirectlyfollowtheF90examplesinthetext. EdAkin, RiceUniversity, 2002 c2002 J.E. Akin viii (cid:13) Index abstractdatatype,15,23,27 rectangular,170 abstraction,19,27 reshape,159 access,36 shape,159 accessrestriction,19 shift,172 accessibility,19 size,159 accessor,18 unknownsize,77 actualargument,56 variablerank,160 Ada,33 arrayoperations,163 addition,56 ASCII,23 ADT,seeabstractdatatype ASCIIcharacterset,77,78,99,163 ADVANCEspecifier,42,103 assemblylanguage,15 agent,18 assignmentoperator,10,39 algorithm,51 ASSOCIATED,15 ALLOCATABLE,15 ASSOCIATEDfunction,76,89 ASSOCIATEDintrinsic,132,134 allocatablearray,160,161 associative,176,177 ALLOCATE,15 asterisk(*),58 allocate,42 ATAN2,13 ALLOCATEstatement,75,93 attribute,105,106,109,121,125 ALLOCATED,15 private,27,125 allocationstatus,75 public,27 ANDoperand,42 terminator,25 area,34 attributeterminator,25 argument attributes,19,27 inout,71 automaticarray,90,160,161 input,71 automaticdeallocation,29 interface,76 none,71 BACKSPACEstatement,76 numberof,76 badstyle,162 optional,76,77 baseclass,121 order,76 behavior,106,109 output,71 binaryfile,163 rank,76 bit returnedvalue,76 clear,75 type,76 extract,75 array,26,60,67,83 set,75 allocatable,160 shift,75 assumedshape,77 test,75 automatic,90,160 bitmanipulation,75 Boolean,168 blanks constant,160 all,78 dummydimension,160 leading,78 flip,170 trailing,78 mask,168,183 Boolean,53 rank,77,159,161,170 Booleanvalue,23 4 bottom-up,4 Drill,106 bounds,159 Global Position,114 bubblesort,93,95 Great Arc,114 ordered,96 Position Angle,114 bug,9 clippingfunction,14,71 CLOSEstatement,75 C,1,33,52 Coad/Yourdonmethod,18 C++,1, 10,14,24,33,52,58,60,77,82,103, colon operator, 56, 61, 62, 78, 160, 163, 167, 123 170 CALLstatement,42 columnmajororder,181 CASEDEFAULTstatement,64 columnmatrix,174 CASEstatement,64 columnorder,162 cases,62 comma,99 centralprocessorunit,73 comment,1,2,7,9,12,52 character,82 commutative,101,176,177 casechange,81 compiler,10,15,91 control,77 complex,10,82,165 fromnumber,81 COMPLEXtype,23,53 functions,78 COMPLEXtype,24 non-print,103 composition,34,36 non-printable,77 conditional,7–9,11,51,58 strings,77 conformable,176 tonumber,81 connectivity,170 characterset,23 constantarray,160 CHARACTERtype,23,26,53 constructor,18,29,34,125,134,135 chemicalelement,25 default,18 circuits,170 intrinsic,18,26,34,39 circularshift,172 manual,36 class,15,19,33 public,37 base,18 structure,26 Date,120,123 CONTAINSstatement,29,33,34,73,76,86 derived,18 continuationmarker,10 Drill,105 controlkey,79 Employee,125 conversionfactors,29 Geometric,120 count-controlledDO,12,13 Global Position,114 CPU,seecentralprocessorunit Great Arc,114 curvefit,91 hierarchy,33 CYCLEstatement,66 instance,33 Manager,125,135 dataabstraction,19 Person,120,123 datahiding,36 polymorphic,133 datatypes,10 Position Angle,109,114 intrinsic,23 Professor,123 userdefined,23 Student,120,123 date,101 classcode DEALLOCATE,15 class Angle,114 deallocate,18,42 class Circle,34 DEALLOCATEstatement,75 class Date,37 debugger,17 class Fibonacci Number,29 debugging,16 class Person,37 defaultcase,64 class Rational,42 defaultvalue,29 class Rectangle,34 dereference,58 class Student,37 derivedclass,121 c2002 J.E. Akin 5 (cid:13)
Description: