Transcription
Fortran#fortran
Table of ContentsAbout1Chapter 1: Getting started with Fortran2Remarks2Versions2Examples2Installation or Setup2Hello, world3Quadratic equation4Case insensitivity4Chapter 2: ArraysExamples66Basic notation6Allocatable arrays7Array constructors7Array nature specification: rank and shape9Explicit shape10Assumed shape10Assumed size10Deferred shape11Implied shape11Whole arrays, array elements and array sections11Whole arrays12Array elements12Array sections12Array components of arrays13Array operations13Addition and subtraction13Function14Multiplication and division14Matrix operations14
Advanced array sections: subscript triplets and vector subscripts15Subscript triplets15Vector subscripts16Higher rank array sections16Chapter 3: C interoperability17Examples17Calling C from Fortran17C structs in Fortran18Chapter 4: Data Types19Examples19Intrinsic types19Derived data types20Precision of floating point numbers21Assumed and deferred length type parameters23Literal constants24Accessing character substrings26Accessing complex components26Declaration and attributes27Chapter 5: Execution Control29Examples29If construct29SELECT CASE construct30Block DO construct31WHERE construct33Chapter 6: Explicit and implicit interfacesExamples3535Internal/module subprograms and explicit interfaces35External subprograms and implicit interfaces36Chapter 7: I/O38Syntax38Examples38Simple I/O38
Read with some error checking38Passing command line arguments39Chapter 8: Intrinsic procedures42Remarks42Examples42Using PACK to select elements meeting a conditionChapter 9: Modern alternatives to historical featuresExamples424444Implicit variable types44Arithmetic if statement45Non-block DO constructs46Alternate return46Fixed Source Form48Common Blocks49Assigned GOTO51Computed GOTO51Assigned format specifiers52Statement functions53Chapter 10: Object Oriented ProgrammingExamples5555Derived type definition55Type Procedures55Abstract derived types56Type extension57Type constructor58Chapter 11: Procedures - Functions and Subroutines60Remarks60Examples60Function syntax60Return statement61Recursive Procedures61The Intent of Dummy Arguments62
Referencing a procedureChapter 12: Program units and file layoutExamples636666Fortran programs66Modules and submodules67External procedures67Block data program units68Internal subprograms68Source code files69Chapter 13: Source file extensions (.f, .f90, .f95, .) and how they are related to the c71Introduction71Examples71Extensions and MeaningsChapter 14: Usage of ModulesExamples717373Module syntax73Using modules from other program units73Intrinsic modules74Access control75Protected module entities77Credits78
AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: fortranIt is an unofficial and free Fortran ebook created for educational purposes. All the content isextracted from Stack Overflow Documentation, which is written by many hardworking individuals atStack Overflow. It is neither affiliated with Stack Overflow nor official Fortran.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1
Chapter 1: Getting started with FortranRemarksFortran is a language used extensively in the scientific community due to its suitability fornumerical computation. Particularly attractive is its intuitive array notation, which makes writingfast vectorised computations easy.Despite its age, Fortran is still actively developed, with numerous implementations, including GNU,Intel, PGI and Cray.VersionsVersionNoteReleaseFORTRAN 66First standardization by ASA (now ANSI)1966-03-07FORTRAN 77Fixed Form, Historic1978-04-15Fortran 90Free Form, ISO Standard, Array operations1991-06-15Fortran 95Pure and Elemental Procedures1997-06-15Fortran 2003Object Oriented Programming2004-04-04Fortran 2008Co-Arrays2010-09-10ExamplesInstallation or SetupFortran is a language which can be compiled using compilers supplied by many vendors. Differentcompilers are available for different hardware platforms and operating systems. Some compilersare free software, some can be used free of charge and some require the purchase of a licence.The most common free Fortran compiler is GNU Fortran or gfortran. The source code is availablefrom GNU as a part of GCC, the GNU compiler collection. Binaries for many operating systemsare available at https://gcc.gnu.org/wiki/GFortranBinaries. Linux distributions often contain gfortranin their package manager.Further compilers are available for example: EKOPath by PathScale LLVM (backend via DragonEgg) Oracle Developer Studiohttps://riptutorial.com/2
Absoft Fortran CompilerIntel Fortran CompilerNAG Fortran CompilerPGI CompilersOn HPC-Systems there are often specialized compilers available by the system provider as forexample the IBM or Cray compilers.All these compilers support the Fortran 95 standard. An overview on the Fortran 2003 status andthe Fortran 2008 status by various compilers is offered by the ACM Fortran Forum and available inthe Fortran Wiki.Hello, worldAny Fortran program has to include end as last statement. Therefore, the simplest Fortran programlooks like this:endHere are some examples of "hello, world" programs:print *, "Hello, world"endWith write statement:write(*,*) "Hello, world"endFor clarity it is now common to use the program statement to start a program and give it a name.The end statement can then refer to this name to make it obvious what it is referring to, and let thecompiler check the code for correctness. Further, all Fortran programs should include an implicitnone statement. Thus, a minimal Fortran program actually should look as follows:program helloimplicit nonewrite(*,*) 'Hello world!'end program helloThe next logical step from this point is how to see the result of the hello world program. Thissection shows how to achieve that in a linux like environment. We assume that you have somebasic notions of shell commands, mainly you know how to get to the shell terminal. We alsoassume that you have already setup your fortran environment. Using your preferred text editor(notepad, notepad , vi, vim, emacs, gedit, kate, etc.), save the hello program above (copy andpaste) in a file named hello.f90 in your home directory. hello.f90 is your source file. Then go tothe command line and navigate to the directory(home directory?) where you saved your sourcefile, then type the following command:https://riptutorial.com/3
gfortran -o hello hello.f90You just created your hello world executable program. In technical terms, you just compiled yourprogram. To run it, type the following command: ./helloYou should see the following line printed on your shell terminal. Hello world!Congratulations, you just wrote, compiled and ran the "Hello World" program.Quadratic equationToday Fortran is mainly used for numerical computation. This very simple example illustrates thebasic program structure to solve quadratic equations:program quadratic!a comment!should be present in every separate program unitimplicit nonereal :: a, b, creal :: discriminantreal :: x1, x2print *, "Enter the quadratic equation coefficients a, b and c:"read *, a, b, cdiscriminant b**2 - 4*a*cif ( discriminant 0 ) thenx1 ( -b sqrt(discriminant)) / (2 * a)x2 ( -b - sqrt(discriminant)) / (2 * a)print *, "Real roots:"print *, x1, x2! Comparison of floating point numbers for equality is often not recommended.! Here, it serves the purpose of illustrating the "else if" construct.else if ( discriminant 0 ) thenx1 - b / (2 * a)print *, "Real root:"print *, x1elseprint *, "No real roots."end ifend program quadraticCase insensitivityhttps://riptutorial.com/4
Uppercase and lowercase letters of the alphabet are equivalent in the Fortran character set. Inother words, Fortran is case insensitive. This behavior is in contrast with case-sensitivelanguages, such as C and many others.As a consequence, the variables a and A are the same variable. In principle one could write aprogram as followspROgrAm MYproGRaM.enD mYPrOgrAMIt's to the good programmer to avoid such ugly choices.Read Getting started with Fortran online: startedwith-fortranhttps://riptutorial.com/5
Chapter 2: ArraysExamplesBasic notationAny type can be declared as an array using either the dimension attribute or by just indicatingdirectly the dimension(s) of the array:! One dimensional array with 4 elementsinteger, dimension(4) :: foo! Two dimensional array with 4 rows and 2 columnsreal, dimension(4, 2) :: bar! Three dimensional arraytype(mytype), dimension(6, 7, 8) :: myarray! Same as above without using the dimension keywordinteger :: foo2(4)real :: bar2(4, 2)type(mytype) :: myarray2(6, 7, 8)The latter way of declaring multidimensional array, allows the declaration of same-type differentrank/dimensions arrays in one line, as followsreal :: pencil(5), plate(3,-2:4), cuboid(0:3,-10:5,6)The maximum rank (number of dimensions) allowed is 15 in Fortran 2008 standard and was 7before.Fortran stores arrays in column-major order. That is, the elements of bar are stored in memory asfollows:bar(1, 1), bar(2, 1), bar(3, 1), bar(4, 1), bar(1, 2), bar(2, 2), .In Fortran, array numbering starts at 1 by default, in contrast to C which starts at 0. In fact, inFortran, you can specify the upper and lower bounds for each dimension explicitly:integer, dimension(7:12, -3:-1) :: geeseThis declares an array of shape (6,3),whose first element is geese(7,-3).Lower and upper bounds along the 2 (or more) dimensions can be accessed by the intrinsicfunctions ubound and lbound. Indeed lbound(geese,2) would return -3, whereas ubound(geese,1)would return 12.Size of an array can be accessed by intrinsic function size. For example, size(geese,https://riptutorial.com/dim 1)6
returns the size of first dimension which is 6.Allocatable arraysArrays can have the allocatable attribute:! One dimensional allocatable arrayinteger, dimension(:), allocatable :: foo! Two dimensional allocatable arrayreal, dimension(:,:), allocatable :: barThis declares the variable but does not allocate any space for it.! We can specify the bounds as usualallocate(foo(3:5))! It is an error to allocate an array twice! so check it has not been allocated firstif (.not. allocated(foo)) thenallocate(bar(10, 2))end ifOnce a variable is no longer needed, it can be deallocated:deallocate(foo)If for some reason an allocate statement fails, the program will stop. This can be prevented if thestatus is checked via the stat keyword:real, dimension(:), allocatable :: geeseinteger :: statusallocate(geese(17), stat status)if (stat / 0) thenprint*, "Something went wrong trying to allocate 'geese'"stop 1end ifThe deallocate statement has stat keyword too:deallocate (geese, stat status)statusis an integer variable whose value is 0 if the allocation or deallocation was successful.Array constructorsA rank-1 array value can be created using an array constructor, with the syntax(/ . /)[ . ]https://riptutorial.com/7
The form [.] was introduced in Fortran 2003 and is generally regarded as clearer to read,especially in complex expressions. This form is used exclusively in this example.The values featuring in an array constructor may be scalar values, array values, or implied-doloops.The type and type parameters of the constructed array match those of the values in the arrayconstructor[1, 2, 3][1., 2., 3.]["A", "B"]! A rank-1 length-3 array of default integer type! A rank-1 length-3 array of default real type! A rank-1 length-2 array of default character typeinteger, parameter :: A [2, 4][1, A, 3]! A rank-1 length-4 array of default integer type, with A's elementsinteger i[1, (i, i 2, 5), 6]! A rank-1 length-6 array of default integer type with an implied-doIn the forms above, all the values given must be of the same type and type parameter. Mixingtypes, or type parameters, is not allowed. The following examples are not valid[1, 2.]! INVALID:[1e0, 2d0]! INVALID:[1., 2. dp] ! INVALID:["Hello", "Frederick"]Mixing integer and default realMixing default real and double precisionAllowed only if kind dp corresponds to default real! INVALID: Different length parametersTo construct an array using different types, a type specification for the array shall be given[integer :: 1, 2., 3d0]! A default integer array[real(dp) :: 1, 2, 3. sp] ! A real(dp) array[character(len 9) :: "Hello", "Frederick"] ! A length-2 array of length-9 charactersThis latter form for character arrays is especially convenient to avoid space padding, such as thealternative["Hello", "Frederick"]! A length-2 array of length-9 charactersThe size of an array named constant may be implied by the array constructor used to set its valueinteger, parameter :: ids(*) [1, 2, 3, 4]and for length-parameterized types the length parameter may be assumedcharacter(len *), parameter :: names(*) [character(3) :: "Me", "You", "Her"]The type specification is also required in the construction of zero-length arrays. From[ ] ! Not a valid array constructorhttps://riptutorial.com/8
the type and type parameters cannot be determined from the non-existing value set. To create azero-length default integer array:[integer :: ]Array constructors construct only rank-1 arrays. At times, such as in setting the value of a namedconstant, higher rank arrays are also required in an expression. Higher rank arrays can be takenfrom the result of reshape with a constructed rank-1 arrayinteger, parameter :: multi rank id
Intel, PGI and Cray. Versions Version Note Release FORTRAN 66 First standardization by ASA (now ANSI) 1966-03-07 FORTRAN 77 Fixed Form, Historic 1978-04-15 Fortran 90 Free Form, ISO Standard, Array operations 1991-06-15 Fortran 95 Pure and Elemental Procedures 1997-06-15 Fortran 2003 Object Oriented Programming 2004-04-04 Fortran 2008 Co-Arrays 2010-09-10 Examples Installation or Setup Fortran .