75% developed

Fortran/Fundamentals

From Wikibooks, open books for an open world
Jump to navigation Jump to search


Introduction[edit | edit source]

Fortran programs are made up of the main program and modules, each can contain subroutines and functions.

Code that should be executed when the program is run should be placed in a program block, like this:

program name_of_program
  ! <variable declarations> ...
  ! <program statements> ...
end program

Indentation is not required, but is recommended. The name of the program must start with a letter, and can otherwise contain letters, numbers, and the _ (underscore) character. Each statement terminates with the end of the line.

Free Form and Fixed Form[edit | edit source]

The Fortran 77 syntax requires that you give 6 spaces before any commands. These 6 spaces originate from the punched card version of Fortran. After the first 6 spaces, you may place additional spaces for indentation if you wish.

However, there is a maximum total line width of 72 characters (including the first 6 spaces). If you require extra space you can put any character (except 0 with some compilers) in column 6; this is called a "continuation character". With punched cards, this meant that you could continue the line onto a second card.

C2345678...
      PRINT *,"This is a really....
     *...long line.

On some compilers you can turn off the 6 spaces rule, and turn off fixed length lines, by specifying "free form" and not "fixed form" mode. If you use the GNU Fortran compiler (gfortran), you can use the -ffree-form command line option when compiling for the same purpose.

Commenting[edit | edit source]

Inclusion of an exclamation mark, !, on a line makes the rest of the line a comment, like this:

 a = b ! this is a comment
 c = d ! this!! is also a comment

In fixed-form mode, you can also mark a whole line as a comment by placing a * or a c in the first column.

Variables[edit | edit source]

See Variables

There are many different types and options for variables, but for now we'll stick to the basics.

real       :: a  ! Decimal number.
integer    :: b  ! Whole number.
character  :: c  ! Single character.

It is recommended to use the implicit none statement before variable declarations to avoid typing errors by forcing the explicit declaration of every program variable.

Mathematical operators[edit | edit source]

See Mathematics

  • Add, subtract, multiply, divide
  +
  -
  *
  /
  • Assignment
  =
  • To the power of ( 2**4 is two to the fourth power = 16 )
  **

The mathematical operators have a certain precedence order:

** [exponentiation] always comes first, it is right to left associative. i.e. 2**3**2 = 512, not 64

Next comes * [multiplication] and / [division], these are left to right associative, i.e., 1.0/1.0/2.0*6.0 = ((1.0/1.0)/2.0)*6.0 = 3.0, not 12.0.

Next in order is + [addition] and - [subtraction], these are left to right associative as well, so x-y+z = (x-y)+z = x+(-y)+z.

Finally comes = [assignment].

Intrinsic functions[edit | edit source]

Fortran has a wide range of functions useful in numerical work, such as sin, exp, and log. The argument of a function must have the proper type, and it is enclosed in parentheses:

x = sin(3.14159) ! Sets x equal to sin(pi), which is zero.

The intrinsic math functions of Fortran are elemental, meaning that they can take arrays as well as scalars as arguments and return a scalar or an array of the same shape:

real :: x(2), pi=3.14159
x = sin([pi, pi/2])

The above program fragment sets the two elements of array x, x(1) and x(2), equal to sin(pi) and sin(pi/2) respectively.

Comparative and Logical operators[edit | edit source]

In if statements, and in some other places, you can code relational operators =, <, >, ≤, ≥, and ≠, respectively as .eq., .lt., .gt., .le., .de., and .ne.. Another way to write these operators would be: ==, <, >, <=, >=, and /=, respectively.

You can also use the logical operators .and., .or. and .not., as well as the logical constants .true. and .false.. When combining these items, do not double up on the dots. For instance, a .and. .not. b is the same as a.and.not.b, but not a.and..not.b.

WRITE statements[edit | edit source]

See Input and Output

write (*,*) "Hello World", variablename, "More text", anothervariable

(*,*) means to use the default output with default options, usually print to screen. Things inside quotes are printed as they look in the code, and the value of the variable is printed. Objects must be separated by commas, and the write statement automatically ends the line by default.

The full formal syntax is:

write (unit=unit_num, FMT=fmt_label, err=label) "Hello World", variablename, "More text", anothervariable

Note that some versions of Fortran don't allow double-quotes, and require single-quotes. An enclosed single-quote can be represented by doubling. For instance, 'don''t'.

The first parenthesized argument to WRITE or READ is the unit number. Unit numbers are associated with input or output streams in a way determined by the operating system. In very old systems, the unit number is the device address. In IBM JCL systems, the association between unit numbers and files are done with JCL DD statements. In other versions, there is some statement that associates files and units. The UNIT= tag may be omitted. If an asterisk is used for the unit number, then the I/O involved is the standard input channel, or the standard output channel.

The second parenthesized argument to WRITE or READ is the record number. Note that this argument, if present, is separated from the unit number by a single quote. If present, this variable defines which record number is read from or written to. For instance,

record_number = 5
write (2, record_number) x, y, z

writes x, y, and z in packed machine-specific format into record number 5. Note, of course, that this usage requires that your OS or Fortran compiler know what constitutes a record. In byte-organized files, the above code would write x, y, and z starting at the file's byte #5.

The third parenthesized argument to WRITE or READ is the format number. If this third argument is present as an asterisk, as above, then the formatting is the obvious default. If you'd rather use a FORMAT statement to format the input or output, then include the statement number for the FORMAT statement. For example:

write (7,1) 'Hello, world!', i, 'More text', x
1 format (A,I,A,F)

Note that a format statement is not executable as an in-line statement. It is only used where referenced by read or write. The fmt= tag may be omitted. The entire argument may be omitted, too. However, if you omit the format argument, the I/O will be performed unformatted, using machine-specific, packed data.

The last parenthesized argument to write or read is the error handler statement label. For instance, if

write (5,err=2) x, y, z

is coded, this means that output is to be unformatted to unit 5. If an error occurs, execution continues at statement 2 (the statement with a statement label of 2 in front of it). If an error occurs, and there is no ERR= argument, then the program abnormally terminates. Thus, ERR= is the closest equivalent of catch in other languages. Although this last argument may be omitted entirely, ERR= can't be omitted from the argument once used.

Example Code[edit | edit source]

See More Examples in Fortran

program nearlyuseless
    implicit none

    real    :: temperature
    integer :: cows

    temperature = 98.6
    cows        = 9
    print *, "There are ", cows, " cows outside."
    print *, "You are probably ", temperature, " right now"
end program

Some versions of Fortran, or in some settings, use format characters. When formatting characters are used, the first character of the line determines how the line is printed. 1 means new page. 0 means 2 line-feeds before the line (double-space). - means 3 line-feeds before the line (triple-spacing). + means no line-feeds before the line (overprinting). And a space means a single line-feed before the line (normal printing).

Here's the same program in archaic form, with this forms-control character:

temperature = 98.6
i_cows = 6
write (*,*) ' There are ', i_cows, ' cows outside.'
write (*,*) ' You are probably ', temperature, ' right now.'
end