Skip to content

Instantly share code, notes, and snippets.

@ansantam
Last active August 29, 2015 14:06
Show Gist options
  • Save ansantam/0864aaec029c887a3e47 to your computer and use it in GitHub Desktop.
Save ansantam/0864aaec029c887a3e47 to your computer and use it in GitHub Desktop.

A Concise Introduction to FORTRAN

Character Set

The FORTRAN character set consists of 26 uppercase and 26 lowercase letters (alphabetic characters), the numbers 0 through 9 (digits), and special characters.

Letters

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

a b c d e f g h i j k l m n o p q r s t u v w x y z

Digits

0 1 2 3 4 5 6 7 8 9

Special Characters

Blank

Equal =

Plus +

Minus -

Asterisk *

Slash /

Left parenthesis (

Right parenthesis )

Comma ,

Decimal point .

Currency symbol $

Apostrophe '

Colon :

Exclamation point !

Underscore _

Double quote “

Operators

Arithmetic operators are evaluated first, followed by the relational operators, followed by the logical operators.

Arithmetic

  • All exponentiations are performed first; consecutive exponentiations are performed from right to left.
  • All multiplication and divisions are performed next, in the order in which they appear from left to right.
  • The additions and subtractions are performed last, in the order in which they appear from left to right.

+ Addition, unary plus

- Subtraction, unary minus

* Multiplication

/ Division

** Exponentiation

Relational

.LT. Less than

.LE. Less than or equal

.EQ. Equal

.NE. Not equal

.GT. Greater than

.GE. Greater than or equal

Logical

Logical operators that can only be used with expressions whose results are logical values (i.e., .TRUE. or .FALSE.)

The priority of .NOT. is the highest, followed by .AND., followed by .OR., followed by .EQV. and .NEQV. Note that .NOT. is right associative, while the other four are left associative.

.NOT. Logical not

.AND. Logical and

.OR. Logical or

.EQV. Logical equivalence

.NEQV. Logical not equivalence

Syntax

  • columns 1-5: label field
  • column 6: continuation field. Used only when a statement is too long to fit on one line (within columns 7 to 72). A statement may be continued on the next line by placing any symbol (like the currency symbol) in the sixth column preceding the continuation.
  • columns 7-72: statement field
  • columns 73-80: Danger! Stay out! (card sequence field)

Keywords

assign, backspace, block data, call, close, common, continue, data, dimension, do, else, else if, end, endfile, endif, entry, equivalence, external, format, function, goto, if, implicit, inquire, intrinsic, open, parameter, pause, print, program, read, return, rewind, rewrite, save, stop, subroutine, then, write.

Reserved words

FORTRAN 77 has no reserved words. Keywords can be used as identifiers, but it is not a good practice.

Identifiers

Identifiers are names used to identify programs, constants, variables and other entities in the program.

They cannot be longer than 31 characters, must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores ( _ ). The first character must be a letter. Identifiers are case-insensitive (except in character strings).

Use meaningful names that suggest what they represent!

Comments

A line that begins with the letter "c" or an asterisk in the first column is a comment. You may also encounter FORTRAN programs that use the exclamation mark (!) for comments. This is not a standard part of FORTRAN 77, but is supported by several FORTRAN 77 compilers and is explicitly allowed in FORTRAN 90. When understood, the exclamation mark may appear anywhere on a line (except in positions 2-6).

Blank spaces

Blank spaces in columns 1 through 5 and 7 through 72 are ignored in FORTRAN 77 (the blank in column 6, the continuation field, is significant). Spaces between keywords are ignored.

FORTRAN 77 allows an optional comma between the label and the loop-control-variable in a DO loop.

Program Structure

PROGRAM  program-name
IMPLICIT  NONE
[specification part]
[execution part]
CONTAINS
   [your functions]
END PROGRAM  program-name

The program is usually referred to as the main program or the main program unit. A program always starts its execution with the first statement of the main program.

When a function is required, the control of execution is transfered into the corresponding function until the function completes its task and returns a function values. Then, the main program continues its execution and uses the returned function value for further computation.

Implicit naming

Implicit naming can cause problems. All variables and constants must be specified explicitly. The following statement:

IMPLICIT NONE

should be used in every program, module, subroutine and function.

Variables

When a variable is used in a FORTRAN program, the compiler associates it with a memory location. The value of a variable at any time is the value stored in the associated memory location at that time.

Variables must be declared at the beginning of a program (or subprogram) in a type declaration statement in the program's specificaction part:

INTEGER  :: n,i

Variable names are identifiers and must follow the rules for forming valid identifiers.

Constants

A constant is a data object whose value cannot be changed. Do not confuse constants with variables that may have constant value.

  • A literal constant is a constant value without a name, such as 3.14.
  • A named constant is a constant value with a name.

FORTRAN allows the programmer to assign identifiers to constants in a PARAMETER statement in the program's specificaction part. This statement has the form:

REAL, PARAMETER :: pi = 3.1415927

In computer programming a statement is the smallest standalone element of an imperative programming language which expresses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).

TYPE statement

Form:

type-specifier list

Declares that the identifiers in list have the specified type. Variables and constants have a type, which can be one of the six intrinsic types. Type statements must appear in the specification part of the program.

Integer Type

Whole numbers, i.e. don't contain commas or decimal point (positive, negative or zero).

Real Type (Single Precision Data)

Ordinary decimal notation (no commas allowed!) or exponential notation. Usually provides seven significant digits.

Double Precision Type

In computations involving iteration or long sequences of calculations, single precision is not adequate to express the precision required. The double precision type provides twice as many significant digits.

Complex Type

In FORTRAN a complex constant is represented as a pair of real constants (a,b) where a and b are single precision constants representing the real part and the imaginary part of the complex number.

Logical Type

Logical values are either true or false. In FORTRAN, they must be written as .TRUE. and .FALSE. Note that the two periods surrounding TRUE and FALSE must be there; otherwise, they become identifiers.

Character Type

Sequences of symbols from the FORTRAN character set. Must be enclosed between double quotes or between apostrophes (single quotes).

DATA statement

In standard FORTRAN all variables are initially undefined, and they should be initialized in the program. This initialization can be done at compile time using the DATA statement of the form:

DATA list1/data1, list2/data2,...

where each list is a list of variables separated by commas, and each data is a list of constants separated by commas used to initialize the variables in list.

DATA statements may appear in the execution part of a program, but it is standard practice to to place them after PARAMETER and TYPE statements in the specifications part.

Functions

In addition to intrinsic functions, FORTRAN allows you to design your own functions. A FORTRAN function, or more precisely, a FORTRAN function subprogram, has the following syntax:

type FUNCTION  function-name (arg1, arg2, ..., argn)
   IMPLICIT  NONE
   [specification part]
   [execution part]
   [subprogram part]
END FUNCTION  function-name

A function is a self-contained unit that receives some "input" from the outside world via its formal arguments, does some computations, and then returns the result with the name of the function. Thus, since the function returns its result via the name of the function, somewhere in the function there must exist one or more assignment statements like the following:

function-name = expression

where the result of expression is stored to the name of the function. A function receives its input values from formal arguments, does computations, and saves the result in its name. When the control of execution reaches END FUNCTION, the value stored in the name of the function is returned as the function value.To tell the function about the types of its formal arguments, all arguments must be declared with a new attribute INTENT(IN). The meaning of INTENT(IN) indicates that the function will only take the value from the formal argument and must not change its content. Any statements that can be used in PROGRAM can also be used in a FUNCTION.

The way of using a user-defined function is exactly identical to that of using FORTRAN intrinsic functions. One can use a function in an expression and in a WRITE. Suppose we have the following function:

 REAL FUNCTION  Average(x, y, z)
   IMPLICIT  NONE

   REAL, INTENT(IN) :: x, y, z

   Average = (x + y + z) / 3.0
END FUNCTION Average

This function takes three REAL formal arguments and returns their average. To use this function, one needs to supply values to the formal arguments. For example, one could write the following:

 ..... = ..... +  Average(1.0, 2.0, 3.0)  * .....

The above expression involves the use of function Average. Since this function has three formal arguments, three values must be presented to the function. Here, the values are 1.0, 2.0 and 3.0 and the returned value is the average of these three numbers (i.e., 2.0). The values or expressions used to invoke a function are referred to as actual arguments.

More about INTENT

It indicates that an argument will receive some input from outside of the function and its value will not, actually cannot, be changed within the function. Since a subroutine cannot return a value through its name, it must return the computation results, if any, through its argument. Therefore, we have three cases to consider:

  • If an argument only receives value from outside of the subroutine, it still has its intent like INTENT(IN). This is the simplest case.
  • An argument does not have to receive anything from outside of the subroutine. It can be used to pass a computation result back to the outside world. In this case, its intent becomes INTENT(OUT). In a subroutine, an argument declared with INTENT(OUT) is supposed to hold a computation result so that its value can be passed "out".
  • Finally, an argument can receive a value, use it for computation, and hold a result so that it can be passed back to the outside world. In this case, its intent is INTENT(INOUT).

Modules

To provide the programmers with a way of packing commonly used functions into a few tool-boxes, FORTRAN 90 has a new capability called modules. It has a syntactic form very similar to a main program, except for something that are specific to modules.

MODULE  module-name
 IMPLICIT  NONE
 [specification part]
CONTAINS
 [internal-functions]
END MODULE  module-name

The structure of a module is almost identical to the structure of a program. However, a module starts with the keyword MODULE and ends with END MODULE rather than PROGRAM and END PROGRAM. A module has specification part and could contain internal function; but, it does not have any statements between the specification part and the keyword CONTAINS. Consequently, a module does not contain statements to be executed as in a program. A module can only contain declarations and functions to be used by other modules and programs. This is perhaps one of the most important difference. As a result, a module cannot exist alone; it must be used with other modules and a main program.

Once a module is written, its global entities (i.e., global PARAMETERs, global variables and internal functions) can be made available to other modules and programs. The program or module that wants to use a particular module must have a USE statement at its very beginning.

Subroutines

A function receives some input via its formal arguments from outside world and computes and returns one value, the function value, with the function name.

In some cases, you do not want to return any value or you may want to return more than one values. Then, FORTRAN's subroutines are what you need. Functions and subroutines are referred to as subprograms. The syntax of a FORTAN subroutine is:

SUBROUTINE  subroutine-name (arg1, arg2, ..., argn)
   IMPLICIT  NONE
   [specification part]
   [execution part]
   [subprogram part]
END SUBROUTINE  subroutine-name

A subroutine is a self-contained unit that receives some input from the outside world via its formal arguments, does some computations, and then returns the results, if any, with its formal arguments.

Unlike functions, the name of a subroutine is not a special name to which you can save a result. Subroutine's name is simply a name for identification purpose and you cannot use it in any statement except the CALL statement. A subroutine receives its input values from its formal arguments, does computations, and saves the results in some of its formal arguments. When the control of execution reaches END SUBROUTINE, the values stored in some formal arguments are passed back to their corresponding actual arguments. Any statements that can be used in a PROGRAM can also be used in a SUBROUTINE.

Unlike functions, which can be used in expressions, subroutines can only be called with the CALL statement. That means, the call to a subroutine must be on its program line rather than somewhere in an expression. The following is the syntax rules of the CALL statement:

CALL subroutine-name (arg1, arg2, ..., argn)
CALL subroutine-name ()
CALL subroutine-name

When a CALL statement is executed, values of actual arguments are passed to those formal arguments declared with INTENT(IN) or INTENT(INOUT). Then, statements of the called subroutine are executed. When the execution reaches END SUBROUTINE, values stored in those formal arguments declared with INTENT(OUT) and INTENT(INOUT) are passed back to the corresponding actual arguments in the CALL statement. After this, the next statement following the CALL statement is executed.

Loops

There are two forms of loops, the counting loop and the general loop.

Counting loop

The syntax of the counting loop is the following:

DO control-var = initial-value, final-value, [step-size]
   statements
END DO

where control-var is an INTEGER variable, initial-value and final-value are two INTEGER expressions, and step-size is also an INTEGER expression whose value cannot be zero. Note that step-size is optional. If it is omitted, the default value is 1. statements is a sequence of statements and is usually referred to as the body of the DO-loop. You can use any executable statement within a DO-loop, including IF-THEN-ELSE-ENDIF and even another DO-loop.

General loop

The general DO-loop is actually very simple. But, to use it properly, you need to be very careful, since it may never stop. The general DO-loop has a form as follows:

DO
   statements
END DO

Between DO and END DO, there are statements. These statements are executed over and over without any chance to get out of the DO-loop. To stop the iteration of a DO-loop, we need something else: the EXIT statement. Since it must be some reason for bailing out a DO-loop, the EXIT statement is usually used with an IF or even an IF-THEN-ELSE-ENDIF statement in one of the following forms. Note that these are not the only cases in which you can use EXIT.

####Implied DO

Arrays

An array is a data structure in which a fixed number of data values (all of the same TYPE) are organized in a sequence. Direct access to each value is possible by specifying its position in this sequence (array elements are indexed or subscripted). This data structure is stored in main memory so that storage and retrieval are fast.

A one-dimensional array has the following important components:

  • A name
  • A type: this is the type of all array elements.
  • An extent: this is the range of the indices or subscripts of array elements. The smallest and the largest indices or subscripts are referred to as the lower bound and the upper bound, respectively.

The extent of an array is simply the following:

 lower bound : upper bound

Thus, if array indices are in the range of 0 and 11, the extent is 0:11; if array indices are in the range of -3 and 21, the extent is -3:21.

The syntax for declaring arrays is the following:

 TYPE, DIMENSION(extent) :: NAME

or:

DIMENSION NAME(extent)
TYPE NAME

where TYPE is the type of the array NAME.

DIMENSION is a required keyword, and extent gives the range of the array indices. With this the computer is instructed to reserve a sequence of n = upper bound - lower bound memory locations. It not only reserves a block of memory locations, but it also associates the subscripted variables with these locations.

In the program we can refer to this entire array of real numbers by using the array variable NAME. We can also access each individual element of the array by means of a subscripted variable formed by appending a subscript or index enclosed in parentheses to the array variable:

 NAME(integer-expression)

where integer-expression is an expression whose final result is an integer. The result of integer-expression, which must be an integer in the range of the extent, gives the index or the subscript of the desired array element.

Input/Output of arrays

There are three ways in which the elements of a one-dimensional array can be read or displayed:

  • Use a DO loop containing an input/output statements.
  • Use only the array name in an input/output statement.
  • Use an implied DO loop in an input/output statement.

More info here:

References

Several websites and the book "Fortran 77 for Engineers and Scientists" - Larry Nyhoff and Sanford Leestma.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment