Section 1: Getting Started

Program Structure

Here is an example of a short Fortran program. The first thing to notice is that it consists of several segments, each consisting of several lines of code. The first segment is the main program, while subsequent ones are subprograms which are called from the main program:

c============================================================
c     First Segment:
c
      program fred   ! Program name - fairly arbitrary
c
c     An example of a simple program.
c
      implicit none
      integer i, j, k
      integer addup
c
      i = 1
      j = 2
      k = addup (i, j)   ! Function call
      call output (k)    ! Subroutine call
      end
c============================================================
c     Second Segment:
c
      integer function addup (a, b)
c
c     A simple function to add together two numbers.
c     NOT the usual way of doing it!
c
      implicit none
      integer a, b
c
      addup = a + b
      return
      end
c============================================================
c     Third Segment:
c
      subroutine output (d)
c
c     Simple subroutine to print a number.
c     Quite unnecessary to do it this way!
c
      implicit none
      integer d
c
      print *, 'Here is the answer: ', d
      return
      end
c============================================================

You will learn more about subroutines and functions later.

Source files, object files and executables

The program shown above is referred to as a source program, because it is human-readable and acts as the source for the binary code that the computer can understand. Source files normally end `.f'. For example, the above program might be stored in a file called myprog.f .

The process of converting a source file to something that a computer can understand is called compiling. A compiler produces a machine code version of your program, which would normally end `.o' , in the above case myprog.o .

Before the compiled program can be run, it is necessary to link it with other machine code programs which are already resident on the machine. These libraries of programs include mathematical functions and functions which handle the keyboard and computer screen. The linked program is referred to as an executable.

Compiling and linking

On most UNIX based systems, the operations of compiling and linking are combined into a single command: f77. For example, to compile and link a program called myprog.f, type:

		f77  myprog.f

The executable file produced is always called a.out unless you specify otherwise. If you want the executable to be called myprog.exe, type:

		f77  -o myprog.exe myprog.f
The -o part of the command is known as a compiler flag, in this case, one which tells the fortran compiler to direct the executable into the file myprog.exe. There are many other compiler flags available each performing specific tasks.

Running a program

To run the program called a.out simply type:

		a.out

If you receive the error 'Command not found' , try the command:

		./a.out

Example

Test out the above operations. Enter the above example using the editor of your choice. Save it as myprog.f and then compile, link and run it. If you encounter problems, make sure you get help from a demonstrator.

Fortran Statements

As already mentioned, a program consists of several lines of text, or statements, which represent a set of commands for the computer to execute. Due to its great history, Fortran is rather strict and expects one command per line of the program. In this respect it differs from most other, younger, computer languages. Fortran is also very strict on the position of commands on the line, and the following rules must be followed:

N.B. It is a common mistake is to let a statement run on beyond column 72, or to begin it before column 7. This can lead to very confusing errors.

As an example, have a look at the following short program:

      program first
c
c234567890
c
c     A very short program.
c
      implicit none
      double precision a, b, sum
c
      print *, 'Hello'
      print *,
     >   'Type two numbers separated by a comma:'
      read *, a, b
      sum = a + b
      print *, 'The sum of ', a, ' and ', b, ' is ', sum
      end

Note:

Hint: Including the comment line c234567890 in your program makes it very easy to identify column 7.

The Program Segment

All programs should begin with a `program' statement and end with an `end' statement. Thus:

      program first
         :      :
c     A very short program.
         :      :
      end

The program statement gives your program a name. The choice of name is usually not too important. The end statement instructs the computer it has reached the end of a segment of code.

Variable Types

There are several types of variable, but we shall mainly be concerned with two of them: integers and floating point. Floating point numbers come in two flavours: single precision (accurate to 7 significant figures) and double precision (accurate to 15 significant figures).

You should always use double precision floating point variables unless told otherwise.

For historic reasons, Fortran implicitly takes all variables beginning with the letters I - N inclusive to be integers, and those beginning with A - H and O - Z as single precision, unless told otherwise. We recommend that you always turn this facility off, by using the `implicit none' statement, as the first line of every program, subroutine and function. This has the effect of forcing the explicit declaration of every variable. This is a good thing because it helps to track down wrongly spelt variables. For example, the following program would give an error if compiled:

      program first
      implicit none
      integer i, j, x, y, height
      double precision a, b, fred, bert
      hieght = 1  ! Wrong spelling
      end

Notes:-

    1. The `implicit none' statement must appear before any variable declarations.
    2. Variable declarations must appear before any executable statements (i.e. statements that actually do things).
    3. Variable names should begin with a letter, and should be restricted to letters, numbers and the underscore character `_'.
    4. Variable names should be limited to 31 characters.
    5. Fortran cannot distinguish between upper and lower case. Therefore, the variable names: FRED, Fred and fred all refer to the same variable.
    6. Single precision variables are declared as `real' or `float' but not as single precision!

Assignments

An assignment statement is one that assigns a value to a variable. For example:

      integer x
      double precision y
      x = 1
      y = 2.0d3

Note here, the use of the double precision scientific notation when assigning the value to y. The character `d' represents the exponent. (`d' is used in preference to `e' which is the single precision equivalent). Thus, the above lines of code actually represent:

x = 1
y = 2.0*103

It is good practice always to use scientific notation for double precision variables. There are some situations, which you will meet later, when it is essential.

Initialising Variables

When a variable is declared, the computer reserves a small part of its memory for it. Generally speaking, the contents of the memory could be any value. This means it is important not to use the variable until a value is assigned to it by your program. This is an extremely common cause of program error!

Expressions

The right hand side of an assignment statement will often be an arithmetic expression. Typical examples are:-

      double precision  a, b, c, d, e
c
      a = 1.0d0
      b = 2.0d0
c
      c = a + b + 2.0d0 * b ** 2
      d = (a + b + c) / (a - b) + 5.7d2
      e = -d

The full set of arithmetic operators is:

+ addition
- subtraction
* multiplication
/ division
** exponentiation

The order of evaluation is often important. In Fortran, as in basic mathematics, the order is:

    1. exponentiation;
    2. multiplication and division (evaluated from left to right);
    3. addition and subtraction (evaluated from left to right).

The order may be controlled by the use of brackets, as shown in the above example. Integers and double precision variables may be mixed in an expression, but this can occasionally cause problems, as outlined in the next section.

Note on Integer Division

Be very careful when dividing two integers. The answer is always truncated. Consider the following simple example:

      integer i
      i = 9 / 5

The result of this calculation is 1, because the result of integer division is always rounded down.

Occasionally, integer division could occur by accident, for example, if integers are mixed with floating point variables in an expression:

      double precision  tempf1, tempf2, tempc
c
      tempc = 20.0d0
      tempf1 = 9 * tempc / 5 + 32  ! Right
      tempf2 = 9 / 5 * tempc + 32  ! Wrong

In the above example, for converting temperatures between centigrade and Fahrenheit, the variable tempf2 will be evaluated incorrectly. Make sure that you understand why. If you don't, please ask a demonstrator.

NOTE: In order to make sure that you do not mix integer and floating point mathematics, a better way to write the above would be:

      double precision  tempf1, tempf2, tempc
c
      tempc = 20.0d0
      tempf1 = 9.0d0 * tempc / 5.0d0 + 32.0d0  ! Better

Simple Input and Output

In Fortran, there are many ways of obtaining input from the user via the keyboard, and of presenting output on the screen. We shall consider only the simplest cases.

For example:

      double precision  a, b, c
      print *, 'Type two numbers separated by a comma: '
      read *, a, b
      c = a + b
      print *, 'The sum of ', a, ' and ', b, ' is ', c

Note the use of quotation marks to enclose text to be printed, and of commas to separate items in both the read and print statements. Do not forget to use the `*', which tells the computer to assume a free format when reading and printing (more about this later).


Exercise 1 - Currency conversion: Part 1

By now you should be tired of reading, so it is time to put what you have learnt into practice and write your first program. You should be able to draw on the examples given above for everything you need. Write a program which converts British pound sterling to Canadian dollars. Assign the exchange rate (currently $2.56 = £1.00 Yikes!!) to the variable convert. Read the amount to be converted from the keyboard and output your answer to the screen.


Program Loops

We often require to repeat the same, or similar, operations many times. For this we use a program loop. In Fortran, the loop construct is referred to as a `do' loop, and looks like this:

      integer i
      double precision delta, alpha
c
      delta = 1.0d-2
c
      do i = 1, 10
        alpha = delta * i        ! The contents of the loop have been
        print *, i, alpha        ! indented to enhance legibility.
      enddo

In this example, the variable `i', sometimes referred to as the loop counter, takes successive values between 1 and 10, and for each value, alpha is calculated and printed. Note that the loop counter is incremented each time enddo is reached. This means that, on completion, `i' will actually contain the value 11.

The do loop can also loop in steps greater than 1 and it can loop backwards. For example:

      do i = 1, 10, 2
        :
      enddo

and

      do i = 10, 1, -1
        :
      enddo

In the first case, `i' will take the values 1, 3, 5, 7 and 9, while, in the second case, `i' will count backwards from 10 to 1.

It is possible for the loop counter to be a floating point number, but this is invariably prone to rounding errors and is not recommended.

Instead of using numbers, the do loop limits can be specified as expressions. For example:

      integer i, j
      j = 100
c
      do i = j, j+10
        :
      enddo

What do you think this does? Finally, do loops can be nested to several levels, as follows:

      integer i, j, k, total
c
      do i = 1, 10
        do j = 0, 100, 5
          do k = 10, 1, -1
            total = i + j + k
            print *, total
          enddo
        enddo
      enddo


Exercise 1(b) - Currency conversion: Part 2

Write a program which shows the conversion between British pound sterling and Canadian dollars for £1 to £25. Use a do loop and the same conversion rate as in Exercise1(a). Output your answers to the screen.


Next: Section 2: Arrays and Intrinsic Functions

Previous: Fortran Workshop


Return to Dr. Alex Brown's Teaching

This page maintained by alex.brown@ualberta.ca of the Department of Chemistry, University of Alberta

Last updated August 8, 2003.