MTMA33

FORTRAN BASICS

2007

FORTRAN 90 Basics
This document provides only a very basic introduction to FORTRAN 90 to allow you to begin writing FORTRAN 90 programs. FORTRAN 90 is actually a very powerful language with many features not described here. For a readable full description of the language see, for example, FORTRAN 90/95 explained, by Metcalf and Reid (Oxford University Press).

1. FORTRAN 90 program structure
A FORTRAN program consists of a sequence of lines of text called statements, which are instructions to the computer. The outline structure of a program is as follows: PROGRAM name Type declaration statements Executable statements END PROGRAM name Here items in italics are not to be taken literally; they indicate the sort of thing that should appear in that position. Executable statements are statements that do things, for example calculate an expression, read or write to a file, etc. Type declaration statements tell the compiler about the types of data the program will use, etc.

1.1. Line structure, and continuation lines
Each line may be up to 132 characters long. Statements may begin at the left hand margin, though it is often useful to indent some statements to make the program more readable. If a statement needs to be more than 132 characters long, or simply to improve the readability of the code, a statement may be continued by up to 39 additional continuation lines. If a line is to be continued then its last non-blank character, or last non-blank before a "!", must be "&".E.g. root = & &

(-b + root_of_discriminant) / (2.0*a)

Blanks have no significance, except within character strings, so blanks can be inserted where desired to make the code more readable. Also, FORTRAN is not case sensitive, except within character strings.

1.2. Comments
Anything to the right of a "!" is regarded as a comment and is ignored by the compiler (except when the "!" appears within a character string). E.g. ! This is a comment line x = x + 1 ! and this statement includes a comment You are strongly encouraged to use comments. A few seconds typing in comments can save hours or days of head scratching when you or someone else tries to understand the code later.
1

FALSE. Types FORTRAN can manipulate several different types of data TABLE 1.TRUE.0) Pairs of real numbers giving the real and imaginary parts of a complex number LOGICAL . delimited apostrophes or quotation marks.14159 Description Whole numbers Numbers that can have a decimal part.1. . Used for Boolean algebra and to control program flow. If a constant is needed in a FORTRAN program its value can simply appear in the place where it is needed. 'Enter a number' ! 20 is an INTEGER constant ! 2. by either Each type of data can come in several kinds.1. Includes very small or large numbers where "times 10 to the power" in scientific notation is represented by "e" COMPLEX (0. CHARACTER 'Hello' "End of run" Strings of characters. which is like a REAL but with more significant figures stored and a wider range of exponents allowed.MTMA33 FORTRAN BASICS 2007 2.1. or .71828 PRINT *. E. Literal constants Constants can have any of the types discussed in section 2. 2. Quantities that FORTRAN can manipulate 2.0. for example with higher precision. i = 20 e = 2.71828 is a REAL constant ! 'Enter a number' is a ! CHARACTER constant 2 . Types of FORTRAN data Type INTEGER REAL Example -3 3.2. FORTRAN_90 also allows the programmer to define their own types of data.. The most useful of these is DOUBLE PRECISION.TRUE.g. for example a type consisting of an integer and a character string that could contain a code number and a name.

Initial values for variables Initial values for variables can be specified in the type statement. c /1. and the first must be a letter. CHARACTER(LEN=20) :: axis_title By default. 2.4. INTEGER :: i.g. E. The type of each variable can be declared in the type declaration statements at the start of the program. j REAL :: heat_capacity The length of a character variable is specified in the type declaration.5. implicitly. b = 2. b. However. 1. INTEGER :: i = 1.. PARAMETER :: pi = 3. Parameters A parameter is a named constant.0/ 2. Variables can have any of the types discussed in section 2. Parameters are useful when the same constant appears in many places in a program.0 An alternative way is to use a DATA statement. nstop /1. any not declared will cause an error message. or n and REAL otherwise.0. Variables Variable names must have between 1 and 31 alphanumeric characters (letters. b. 200/. the programmer can change it between runs. Doing this speeds up program development enormously by catching a lot of bugs that would otherwise be difficult to track down. Then all variables must be declared.MTMA33 FORTRAN BASICS 2007 2. a.g. However. It cannot be changed by the program as it runs. Choosing variable names sensibly will greatly help the intelligibility of your code. c DATA i. k.g. for example as an array size.3. nstop = 200 REAL :: a = 1. PARAMETER :: npoints = 1000 REAL.14159 3 .0.0. nstop REAL :: a.g.1. j. INTEGER.0.. l. A parameter type is declared and its value assigned in a type statement. c=1. E. to be INTEGER if their name starts with i. you are strongly encouraged to override this by inserting the statement IMPLICIT NONE before your type declaration statements. E. 2. INTEGER :: i. underscores and numerals). variables whose type is not specified are assumed. m. E.

Numeric operators High precedence ** Exponentiation * Low precedence Multiplication / Division .. Assignment Assignment statements are of the form variable = expression This means evaluate the expression on the right hand side and put the result into the variable appearing on the left hand side. However volume = (4/3) * pi * r**3 will yield the wrong result because the integer subexpression (4/3) will be evaluated first as 1. E. Any value that the variable had previously is overwritten and lost.1. Numeric operators Expressions are built up from operators and operands.0 is a perfectly valid assignment statement and involves no contradiction. a-b+c but a**b**c means a**(b**c) means (a . except for repeated exponentiations. x = x + 1. The "=" sign thus has a slightly different meaning from its usual mathematical meaning. Calculations 3.g. Usually expressions do as you might expect when combining different types in one expression: INTEGERSs are converted to REALs when they are to be combined with REALs and REALs are converted to COMPLEX when they are to be combined with COMPLEX. the result of 2**(-3) is 0. a variable is undefined. x = y + b*z**2 the operators are evaluated in the order of precedence given in table 2. the result of 8/3 is 2.g. Operators with equal precedence are evaluated left to right. Then it becomes defined. E.e. 3.MTMA33 FORTRAN BASICS 2007 3.Subtraction + Addition When several operators appear in an expression. until it appears on the left hand side of an assignment statement or is read in a READ statement. Unless it has been given an initial value in a type or data statement. e. and should be used to avoid ambiguous-looking expressions like b/2.0*a The results of INTEGER arithmetic are always integers.g. The numeric operators built into FORTRAN are TABLE 2.b) + c Parentheses can be used to override the default order of evaluation of operators. Undefined variables cannot be used in expressions. the result of -8/3 is -2. For example. In the case of division not yielding an exact integer the result is truncated towards zero to give an integer. has no definite value. i.2. 4 .

0 respectively. 5 . surf ! fun. 3. Logical operators and expressions Logical expressions can be combined using Boolean logical operators. then a < b would have the value .MTMA33 FORTRAN BASICS 2007 3. . summer = sun . Logical operators High precedence . .and.and. Relational operators Relational operators compare two numerical expressions and return a logical value.g. These are.and.0 and 2.g.FALSE. Logical negation Logical intersection Logical union Logical equivalence and non-equivalence E.not. sun and surf ! are LOGICAL variables Relational expressions may be included in logical expressions. .neqv.TRUE.eqv. Low precedence . in order of precedence TABLE 4.0 ! temperature is REAL ! sun is LOGICAL In this case any relational operators take precedence over logical operators. TABLE 3. Relational operators < <= == /= > >= Less than Less than or equal to Equal to Not equal to Greater than Greater than or equal to For example. fun = sun . E. and .3..4. if a and b are real variables equal to 1. while a == b would have the value .or. temperature > 22.

Intrinsic functions FORTRAN has many built-in functions that can be used in computing expressions.5. if word1 = 'hot' and word2 = 'pot' then word1//word2 has the value 'hotpot' and word1(1:2)//word2(2:3) has the value 'hoot'. Some of the most useful are given in table 5.a2..g.) MAX(a1.6. TABLE 5. 3....MTMA33 FORTRAN BASICS 2007 3..b) INT(a) NINT(a) ABS(a) SQRT(a) EXP(a) LOG(a) SIN(a) COS(a) TAN(a) ATAN(a) SINH(a) COSH(a) TANH(a) REAL(i) REAL(z) AIMAG(z) CONJG(z) LEN(y) Minimum of the arguments Maximum of the arguments Absolute value of a times sign of b Integer part of a (truncated towards 0) Nearest integer to a Absolute value of a Square root of a e to the power a Natural logarithm of a Sine of a Cosine of a Tangent of a Arctangent of a Hyperbolic sine of a Hyperbolic cosine of a Hyperbolic tangent of a Convert INTEGER to REAL type Real part of a COMPLEX value z Imaginary part of a COMPLEX value z Complex conjugate of z Length of a character string y 6 . E.a2.) SIGN(a. Intrinsic functions MIN(a1... Character expressions Character variables can be manipulated by concatenation and by extracting substrings.

. can be of any type. It has the form IF (logical_expression) action_statement For example. expression2. variable1. b PRINT *. a.MTMA33 FORTRAN BASICS 2007 4. (The program can be made to stop elsewhere by a STOP statement. 5. READ *. PRINT *. expression1.. The program stops when it reaches the END PROGRAM statement. expression2. When the program reaches the READ statement it pauses and waits for the data to be typed in. The expressions expression1. Printing To print results to the monitor a PRINT statement is used. Control statements Normally FORTRAN statements are executed in top-to-bottom order. Note that it is advisable to have a PRINT statement before the READ statement otherwise you won’t know that the programme is waiting for you to enter something! E. . Control statements are what give computer programs the power to perform very complex calculations... 'Their sum is '. ..1. a + b 5.2. IF (leapyear) ndays = 366 7 .1. 'Enter two REAL numbers' READ *.g. 4.) Control statements allow the program to depart from the normal top-to-bottom exectution order. . variable2. Reading To read data from the keyboard a READ statement is used. PRINT *. Printing and Reading 4... The IF statement The IF statement is the simplest control statement.

IF constructs can be given a name. E..g. See Example 4 in the appendix. ELSE statements_4 ENDIF There may be any number of ELSEIF blocks. and more complex conditional code included. including none. helping both the programmer and the compiler's error checking. If it is omitted then there is no action if the logical expression in the IF statement is false.. swap: IF (a < b) THEN temp = a a=b b = temp ENDIF swap 8 . IF constructs may be nested within each other to handle complicated cases. The IF construct Alternative cases can be catered for.MTMA33 FORTRAN BASICS 2007 5. by using the IF construct..2. This is useful in long and complicated programs. The ELSE block is also optional. Indentation is recommended to keep the code readable. IF (logical_expression_1) THEN statements_1 ELSEIF (logical_expression_2) THEN statements_2 ELSEIF (logical_expression_3) statements_3 .

GOTOs should be used only when absolutely necessary.. last. timeloop: DO step = 1. In the target statement the label must appear in the first 5 columns. Also DO loops can contain IF constructs and IF constructs can contain DO loops.MTMA33 FORTRAN BASICS 2007 5. 9 . etc. and step are INTEGER expressions. The DO construct The DO construct allows a sequence of statements to be repeated a number of times.TRUE.3. nstop statements ENDDO timeloop DO loops can be nested one within another. last. E. Usually the target statement is of the form label CONTINUE CONTINUE is a do nothing statement that exists mainly to make target statements clearer (and as an alternative terminating statement for DO loops). otherwise the loop will carry on for ever. Like IF constructs. An alternative form of the DO construct is DO WHILE(logical_expression) statements ENDDO The loop is entered or re-entered only if logical_expression is .FALSE. This form of the construct is useful when the number of iterations is not known before entering the loop. otherwise they lead to unstructured code that is difficult to read and error prone.g. One form of the DO construct is DO control_var = first. The statements are executed times (this may be 0 times). 5. DO loops can be given names to improve the readability of complex codes and to help the compiler's error checking. then it takes the default value 1.. On successive iterations control_var takes the values first. The target statement may be either before or after the GOTO statement. Obviously the calculations carried out by statements must result in the logical_expression eventually becoming . and first. It has the form GOTO label statements label statement The label is a string of up to 5 digits. step statements ENDDO Here control_var is an INTEGER variable. control_var may not be explicitly modified by any of the statements within the loop. . step may be omitted from the DO statement.4. The GOTO statement A GOTO statement transfers control to another part of the program. See Example 5. then first+step.

a(1:10) = c(11:20. For example a = 2.0*b ! a and b are arrays takes each element of the array b.i) + d(n+1:n+10) + 1. E. FORTRAN 90 can also perform calculations on whole arrays using a single statement.. a(2). REAL :: a(0:100) PARAMETERS that are defined before the array is declared can be used in declaring the array.g. Arrays Arrays are a way of giving lots of data values of the same type the same name. . E. INTEGER. 10 .g. but this can be overridden by specifying a lower bound. Subarrays may also be manipulated by specifying a range of indices. multiplies it by 2. PARAMETER :: rows = 10.MTMA33 FORTRAN BASICS 2007 6.2. The index must be an integer. The number of indices needed is the dimension of the array. The arrays a and b must be conformable.. allowing lots of similar calculations to be done with a small amount of code. which may range from 1 to 7.0 PRINT *. in the obvious way. The elements of an array are identified by indices. a(3) = SQRT(2.g. columns) 6..0) + b f= c(1) + c(2)*x + c(3)*x*x Arrays become powerful computing tools when the index is a DO loop control variable.e..' a = '. the subarrays must be conformable. E.. E. See Example 6 and Example 7. a(1:10) Again. Note that a scalar is conformable with any array. By default the lowest index is 1.g. and stores the result in the corresponding element of array a. E.0. columns = 25 REAL :: matrix(rows. i. Array declaration The size and shape of an array is specified in the type statement.. and the rules for naming them are the same as for non-array variables (called scalars). 6.1. Calculations using arrays An individual element of an array can be used in calculations by specifying its index. a(10).. Arrays may be of any type. REAL :: a(10) defines an array whose elements are a(1).g. have the same shape and size.

Usually the CALL and SUBROUTINE statements should have the same number of arguments. dummy2. and the corresponding argument should have the same type and shape and size. either directly or indirectly.1. SUBROUTINE name(dummy1.MTMA33 FORTRAN BASICS 2007 7.) has the effect of executing the subroutine statements with the dummy arguments replaced by the corresponding actual arguments. Yet others may be intended for passing data both ways. See Example 11. including arrays. The actual arguments may be constants or variables. except that it can include some dummy arguments. actual2. See Example 10. or INOUT. . and reduces the risk of introducing bugs. SUBROUTINEs may CALL other SUBROUTINEs. The clarity of the code may be improved and the compiler's error checking helped by specifiying the intent in the subroutine's type declaration statements.) Type declaration statements Executable statements END SUBROUTINE name The dummy arguments provide one way to pass data between the main program and the subroutine. See Example 10 and Example 11. Subprograms A piece of code that needs to be executed at several different places in a program can be put in a subprogram and that subprogram called from the main program at the appropriate places.) A statement of the form CALL name(actual1. However. The dummy arguments must be variables. 11 . When an argument is an array it is often convenient to pass its shape and size information as arguments too. The INTENT may be IN. . and so you are encouraged to place well-defined subtasks in subprograms even if they are used only once.. OUT. Subroutines A SUBROUTINE has a very similar structure to a PROGRAM. special steps must be taken if a SUBROUTINE is required to call itself. The use of subprograms also produces more modular and structured code.. This reduces program length and programmer effort.. Others may be intended solely for passing results out of the subroutine and need not be defined on the way in.. FORTRAN allows two kinds of subprogram: SUBROUTINEs and FUNCTIONs 7. Some arguments may be intended solely for passing data into the subroutine and should not be modified by the subroutine. (Another way is through modules.

and that somewhere in the executable statements name must be assigned a value. Functions A FUNCTION has a similar structure to a SUBROUTINE. dummy2.MTMA33 FORTRAN BASICS 2007 7. See Example 8. If you need to do this then it's better to use a SUBROUTINE. 12 .) Type declaration statements Executable statements END FUNCTION name The important differences are that a FUNCTION has a type.. It is poor programming practice to change the values of the dummy arguments within a FUNCTION.2. A FUNCTION is invoked by using its name in a similar way to using any intrinsic function. type FUNCTION name(dummy1. ..

5)') 1005. Files Data may be be written to or read from files stored on the computers discs.23 WRITE(6. OPEN(unit. right adjusted Width w. can be specified in a FORMAT statement and referred to by a label.X. depending on the format parameter of the READ or WRITE statement.I2)') 22. and each with 12 characters including leading blanks. 13 . producing 10 lines of output.d Ew..14 WRITE(6.'(F12.14000 0./.10050E+ 03 HELLO 22 23 22 23 Longer format strings.MTMA33 FORTRAN BASICS 2007 8. TABLE 6.5)') 3.g.I2)') 22. d decimal places Scientific notation.'(E12. format2) outputlist Here inputlist is a list of variables to be read in from the file. d decimal places Character string Skip a character New line Example WRITE(6. format1) inputlist WRITE(unit2. each with 10 numbers.23 Output 123456 3. and 5 decimal places.'(A)') 'HELLO' WRITE(6.5) In this example the FORMAT statement specifies 10 numbers to be written. and outputlist is a list of variables and constants to be written out to the file. E. A file may be opened for reading or writing using an OPEN statement. or format strings that are to be used repeatedly. each in floating point format.'(I6)') 123456 WRITE(6.'(I2. file = filename) Here unit is an INTEGER expression (usually in the range 1-99) and filename is a CHARACTER expression. Then a READ statement does its best to read the data whatever format it is in.900) a(1:100) 900 FORMAT(10F12. There are various ways of specifying the format of the data to be read or written. Format specifiers Type INTEGER REAL REAL CHARACTER Edit descriptor Iw Fw. Subsequent READ or WRITE statements then refer to the file via the unit number.d A X / Description Width w. The simplest case is when the format parameter is an asterisk (list-directed I/O). so the specified format is recycled 10 times.0 WRITE(6. READ(unit1. and a WRITE statement choses a reasonable format for the data being written at that moment.'(I2. The WRITE statement writes 100 numbers. The user can control the format explicitly by specifying it in a CHARACTER string built up from edit descriptors separated by commas and enclosed in parentheses. WRITE(6.