Fortran/Beginning Fortran

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

← Hello world | Fortran variables →


Part of the Fortran WikiBook

Introduction[edit]

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]

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.

 12345678...
       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.

Spaces[edit]

Consistently separating words by spaces became a general custom about the tenth century A. D., and lasted until about 1957, when FORTRAN abandoned the practice. —Sun FORTRAN Reference Manual

Spaces are ignored in FORTRAN.

Commenting[edit]

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]

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  A !whole number.
  CHARACTER  A !single character (strings are coming up)

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]

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].

Comparative and Logical operators[edit]

In IF statements, and in some other places, you can code relational operators =, <, >, ≤, ≥, and ≠, respectively as .EQ., .LT., .GT., .LE., .GE., 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]

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'record', FMT=format, ERR=statement) "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,

   iRecordNumber = 5
   WRITE(2'iRecordNumber) 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 line number. 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]

See More Examples in Fortran

  PROGRAM nearlyuseless
    IMPLICIT NONE
    REAL :: temperature
    INTEGER :: cows
    temperature = 98.6
    cows = 9
    WRITE (*,*) "There are ", cows, " cows outside."
    WRITE (*,*) "You are probably ", temperature, " right now"
  END PROGRAM nearlyuseless

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
   iCows = 6
   WRITE(*,*) ' There are ', iCows, ' cows outside.'
   WRITE(*,*) ' You are probably ', temperature, ' right now.'
   END

Conclusion[edit]

So there you have it, some very simple Fortran knowledge. Enjoy.