Section L3.2: Writing Simple Fortran Programs

This section is intended to get you started writing elementary programs in Fortran. We will not attempt to explain all the peculiarities of the Fortran programming language. We will try and explain the logic behind those parts of the language which are easily explained, and treat as arbitrary rules to be learned by rote those which are either actually arbitrary, or too time consuming to attempt to explain.

Examples will be given on the assumption that the Edinburgh Portable Compilers EPCF90 compiler is being used on a Unix system.

The aim is to get you writing simple programs quickly, not to teach you all about writing complex programs. If you want to find out more about the Fortran 90 (F90) language and `real' programming, we will provide hypertext links and a bibliography which you can follow up.

A First Program

Here is the world's simplest `useful' Fortran program:
program hello
print *, 'Hello World!'
end program hello

Program structure

The program starts with the word `program' simply because F90 programs must do so. The program must also be given a name, so we have called it `hello'. It must also end with the words `end program', hence the last line. The use of the program name in the last line is optional in most F90 dialects, but it is good practice to include it. (Your lecturer, however, often gets lazy and omits it. In fact just the word `end' is sometimes enough, but you should try to follow what everyone agrees is good practice!)

A program which consisted just of the first and last lines would be a `syntactically acceptable' program, i.e. it could be compiled and run as described below. However, it wouldn't do anything, and so would be pointless.

The `useful' bit of the program is the middle line:

print *, 'Hello World!'
What this does is to print on the computer screen the text:
`Hello World!'
This instruction is formally called a `procedure call'. It causes something to be done; what is does is predefined by the word `print' which the language recognises as meaning `print or otherwise display some information'.

What is printed is determined by the programmer-supplied text included between the two quote symbols. (NB these are both the same single closing quote on the keyboard.) Any text (except for another single quote!) which appears there will be `printed out'. A piece of text in quotes is referred to as a `text string' or `character string' or sometimes just a `string'.

And the `*,' ? For the time being, please just accept that it is necessary. If you leave it out, the program will not work!

For future reference: you will encounter other types of procedure call in the language. All have the properties that (a) what is done is predefined and associated with the name of the procedure, here `print'. How it is done, or with or to what is usually specified by the programmer, as is the case here with the text to be printed.

Running the program

If you click on this link you will get a copy of the program in your WWW browser. You should have learned how to save this in you own filespace. Do this. By default the program will be stored in a file called `hello.f90'. All F90 programs should be stored in files with the `filename extension' .f90 or else they will not be recognised as Fortran programs.

Once you have saved the program it must be translated from a form which you can read (sometimes called the `source language') into a form which the computer can run. This process is called `compilation'.

Assuming you have saved the hello.f90 in your current working directory, to compile the program type:

epcf90 hello.f90
`epcf90' is the name of the command which runs the compiler. It is always followed by a space and then the name of the source language file. (And of course `return' at the end!) The computer will print a number of messages which should look something like this:
... epcf90 hello.f90
EPC Fortran-90 Version 1.5.1.7 Sparc:031097:145225
Copyright (c) 1993-1997 EPCL. All Rights Reserved.
hello.f90
   program HELLO

3 Lines Compiled
If you look at your files, you will find that there are a number of new ones, mostly with peculiar names. One in particular will have the name a.out and this is the `compiled' or computer runnable version of your program. To run (`execute') this just type:
a.out
and see what happens.

Things to Try with the Simple Program

Load the program into a text editor, e.g. by typing:
 textedit hello.f90 

Change the message

Change the text in the quotes to something else. `Save' the program file from the editor, compile it again and type a.out, which will execute the new version of the program.

Add another message

You can include as many `print' instructions of the form shown as you like, provided that each is on a separate line. Try adding another message this way.

EPCF90 and most versions of Fortran also allow instructions to be separated by a semicolon `;'. Thus the following are equivalent:

print *, 'This is my 1st program..'
print *, 'Hello!'
And:
print *, 'This is my 1st program..' ; print *, 'Hello!'
Try these two forms.

Printing on the same line

You may have noticed that the two messages above appeared on different lines even when the two instructions were on the same line. To print to messages on the same line they could either be made into a single piece of text within one pair of quotes, or written as two strings of text separated by a comma in one print instruction, i.e.:
print *,  'This is my 1st program..' , 'Hello!'
Try this. This has a somewhat different effect from having the same message in one text string.

Add a message to the reader of the program

It cannot be stressed too strongly that a good program is easy to follow and makes sense to the reader! You can add `comments' which do not cause the program to take any additional action, but which help the reader to follow what is going on. Any line or part of a line beginning with an exclamation mark `!' is treated in this way.

A properly commented version of hello.f90 is here.

program hello
! Very first example program
! Written by JWP, September 1998
!
print *, 'Hello!'  ! A single procedure call
! This will print a message on the screen
!
end program hello
If you compile this you will find it behaves exactly as the shorter version did.

Arithmetic in Programs

As well as printing messages, computers can of course do arithmetic. Here is a simple program to do a calculation:
program arithmetic
! program to do a calculation
! Written by JWP 29/10/98

print *, 'This program calculates 23.6*log(4.2)/(3.0+2.1)'
print *,  23.6*log(4.2)/(3.0+2.1)
! Note the effect of the presence or absence of quotes! 
end program arithmetic
You can copy it from here.

Save, compile and run this program.

Important Point! Notice the difference between how 23.6*log(4.2)/(3.0+2.1) is treated:

In the first case it is just a string of text and is, in the context of a `print' instruction, simply displayed exactly as it appears.

In the second it is treated as an expression and is evaluated using the computer's rules for arithmetic. These are more-or-less the same as the conventional rules but include the following:

Two possible pitfalls lurk for the unwary:

The point about being able to print two quantities in the same print instruction may now become more obvious. We can have both expressions and strings in the same instruction so as to print on the same line, e.g.:

print *, 'This value is ', 23.6*log(4.2)/(3.0+2.1)

Variables

This is a key section which you must understand before proceeding further! Seek help if you are not entirely clear about it after trying the examples.

Consider the following program which you should copy from here:

program variable
!this program evaluates an expression
!written by JWP 28/10/98

real :: x ! This defines a variable called x
!
x = 23.6*log(4.2)/(3.0+2.1) ! This gives it a value
!
print *, 'The value of x is ', x 
! .. and then print it out
end program variable
The overall effect of this is essentially the same as the previous program, except that it involves a new kind of entity, vital to effective programming, called a variable. It is so called because the value which it takes can be changed by equating it to different expressions on the right hand side of an instruction which always takes the form:
variable_name = expression
The form of this assignment instruction is identical to that of evaluating a formula, as discussed in section 3.1. It is convenient to think of a variable in this context as being the same as a variable in a set of equations, although it is in fact a more general and flexible concept than that. At the very least, the use of variables facilitates the writing and developing of programs, and makes them easier to understand.

Consider the use of a program to evaluate expressions involving variables whose values depend on other variables, i.e. a set of equations. This involves a slightly modified version of the previous program:

program variable
!this program evaluates two expressions and prints the result
!written by JWP 29/10/98

real :: x, y ! This defines variables called x and y
!
y = sqrt(23.6)              ! calculate y
x = 23.6*log(1.0+y)/(3.0+y) ! calculate x which involves y
!
print *, 'The value of x is ', x 
print *, 'The value of y is ', y 
! .. and then print them out
end program variable
You can copy this program here.

The instruction:

real :: x, y 
is called a declaration of the variables x and y. It consists of the word real to indicate that the variables will be used to represent general or real numbers (as opposed to whole numbers or integers, which can also be be used in certain circumstances, see later).

It is followed by a list of the names to be given to the variables. These can be any combination of letters or numbers, but must start with a letter. The names may not include spaces, but the underscore character `_' may be used and is very useful in improving readability.
Invalid variable namesValid variable names
1stfirst
not correctthis_is_correct
_invalidx4
a-bad-nametemperature
no.dots.allowedvolume

The two colons `::' are part of the illogical richness of Fortran. They may sometimes be left out, but this is not advised.

You should try to choose variable names which help the readers understanding of the program. In general you should not use meaningless name like `x' and `y', unless these have been used in the specification of the problem. Where standard symbols exist, e.g. `P' for pressure or `T' for temperature, use these with variants, e.g. T1, T2 or use descriptive names, e.g. T_reactor, Column_Pressure. Names can be up to 31 characters long, but typing very long names becomes tedious (and they can be mis-spelled). NB. Fortran is case insensitive. Thus FIRST, First, and first all refer to the same variable.

Implicit none

There is a naming convention in Fortran, which states that all undeclared variables starting with letters I through to N are assumed to be integers, another variable type. Otherwise it is assumed to be a real variable. This convention can lead to some very confusing runtime errors. To avoid errors put the statement
implicit none
at the top of every program. This is a sign of good programming style or practice.
This statement should be at the top of every program. Its absence will result in penalties in tests or handins.

Parameters

The programming language also allows for the use of parameters which are named entities, like variables, but are given a value once, and may not have their values changed. Their use is explained in the gas law example.

Parameters are declared in a similar manner to variables, but must be given their constant values at the same time as they are declared. For example, pi should remain constant throughout a program:

real, parameter :: pi=3.14

In this very simple program we have not really exploited the concept of variables whose values may be changed. It would have been possible to decide that the entity we have called y was a parameter. This has been done in this second version of the program. since a name like `y' is typically associated with the unknown in a problem, the name has been changed here, although this is not strictly necessary.

program variable
!this program demonstrates the use of parameters
!written by JWP 29/10/98

implicit none

real :: x ! This defines variable called x 
real, parameter :: fixed_y = 4.86 
!
x = 23.6*log(1.0+fixed_y)/(3.0+fixed_y) ! calculate x which involves y
!
print *, 'The value of x is ', x 
print *, 'The fixed value of y is ', fixed_y 
! .. and then print them both out
end program variable

Program Structure

Good programming practice (and sometimes the Fortran standard) dictates that a program should always have the same rough structure. The above example shows this structure.

More Programs

All the programs you have been shown so far are `correct', i.e. they should compile without any error messages and run to print out the required results. The first programs you write will almost certainly not be correct!

To give you practice in `debugging' programs, here is one which will fail to compile.

program crunch
! there is/are something(s) wrong with this program
! find out what and correct it
!written by JWP, 23/10/98

implicit none

real :: a, b, c
a = 10.0
b = 23.5
c = a*b
print *,'What is wrong with this?
print *, 'Nothing now..'
print *, c is, c
!
end program crunch

And here is another which may appear to be correct but will fail.

program crunch_again
! This program has a different kind of error from the first one

!written by JWP 23/10/98

implicit none

real :: a,b,c
print *,'Does this work?'
a = 10.0
c = 3.5+a
c = c*b
b = 23.0
print *, 'a, b and c are:', a, b, c
!
end program crunch_again

Copy these, try them and correct them.


Return to Modelling Lab

Course Organiser
Last Modified 4/9/00