Introduction

The aim of this course is to introduce you to the development of computer programs and to provide youwith a working knowledge of Fortran 95.

The name Fortran is a reduced form of Formula translator, which gives an immediate clue to the origins of this programming language. It was devised by IBM during the 1950s as a language for general scientific computational use. It has continued to develop in the form of:

  • Fortran 66 (now totally abandoned)
  • Fortran 77 (still widely used, but obsolete and superseded by more recent versions of the language),
  • Fortran 90 (a powerful, modern language)
  • Fortran 95 (Fortran 90 with a few additional advanced features)

The numbers 66, 77, 90 and 95 indicate the years of various revisions and updates of the standards of the language. There are other versions, such as HPF (high performance Fortran). The standards of Fortran 2003, which will replace Fortran 95 in due course and is a very powerful object-orientated language, have now been published, and Fortran 2003 compilers are becoming available. The norms of a revised form of Fortran 2003, Fortran 2008, are currently being developed.The continued existence of Fortran after many other languages, popular in their time, have come and gone is confirmation of its established strength in the scientific area. Fortran is not, however, particularly suitable as a non-scientific general-purpose language of for use in equipment control, commerce, text management, etc., where more appropriate alternatives are available. It is widely used within the physics community, though, and remains the premier language for demanding numerical calculations.

The present course is intended for self study. It is divided into six parts. The first five cover all the fundamentals. Other elements of the language are briefly described in the last one. It is expected that you study each part one after the other, starting with Part 1 (whose content is absolutely essential.) You’ll find it useful to come back to Parts 1 and 2, as a revision, when you reach the end of Part 3, and again to Part 1 to 4 when you’ll reach the end of Part 5. A number of exercises are proposed throughout the course (except in the last part). Practice is essential in programming, and these exercises should immensely help you acquiring the language. Full model solutions are provided for each exercise, on the web page of the course:

and/or in the worksheets distributed with the course. You should try to complete each exercise without looking at the solution, but if you get stuck a quick look may give you a valuable hint. Compare your programs to the model solutions and think about any difference. This will help you improving your programming style.

The course assumes that you use the Plato development environment of the Salford package for doing the programming exercises. This package is available on the University Networked PC Service. Instructions for accessing and using it are given at the beginning of the notes and in Part 1 of the course. However, if you prefer, you can equally well do the exercises either on the University Unix Service or using your own computer.

The course covers enough material to provide you with a basic knowledge of Fortran 95. It does not offer, and does not aim at offering, a comprehensive overview of the language. Among the many possibilities of Fortran 95 not covered at all are the constructs and intrinsic functions related to the use of strings of characters, of derived structures, and of pointers and linked lists. Object-oriented programming is completely ignored. While the most important features of the language are mentioned, many of the related details are left out. Readers who need to program extensively and seek to develop an expert knowledge of Fortran 95 are advised to consult advanced texts. Various issues concerning numerical computations, of great importance in practice, are not mentioned at all in these notes. They will be addressed in the lectures associated with the course.

Fortran 95 enables you to program complicated mathematical expressions in a relatively simple way, and without knowing much about the language besides the all important distinction between integer, real and double precisiontypes of variables. Unfortunately, this does not mean that you will always find it easy. You may want to allow plenty of time to get started and pass through Part 1, particularly if you have little programming experience. If you already know another language, be careful not to be confused by the differences in the syntax and in the conventions of Fortran. A list of common programming errors is given in the Appendix.

Finally, here is some general advice about learning a programming language:

Firstly, get started with the help of someone or by taking an introductory course such as this one. You learn programming by programming, not by reading notes, so do exercises and problems. Look at examples and imitate them. Analyse programs written by experts. To learn more about the language, peruse a good reference manual every now and then. After you’ll have gained confidence, attack a project (a real project, but not one which is too ambitious, you don’t want to waste days on trying to get a useless program to work). Develop your codes in small steps; test them and test them again as they grow. Unavoidably, you’ll make errors. If your program does not behave as expected for unknown reasons, follow what the computer is doing by printing out intermediate values, or write a short test program to make sure that you properly understand the features of the language you are using. If you are completely stuck, ask an expert. And in any case, never hesitate to discuss with others how to program what you require if you are not quite sure how to do it well.

Using theSalford Plato Fortran Package

The Salford package provides a complete development environment, Plato, in which Fortran programs (and, incidentally, also C++ programs if the file concerned has a .cpp extension) can be written, edited, compiled, linked (built), debugged and executed.

At the compilation stage the program as typed by you is checked for syntax errors and translated into an intermediate form to produce a so-called object file (such files will have an .obj extension) if no errors are found. At the linking or build stage your compiled program is converted into a final machine-understandable executable form (with an .exe extension) containing all the required support for input/output, code to evaluate functions intrinsic to the Fortran language, etc. Whereas your original typed program, if correctly written, should be understandable to any standard Fortran 95 compiler the final, executable form of your program is specific to a particular machine type.

Before beginning to use Plato it is advisable to create a new folder on the J: drive e.g. J:\fortran in order to store your various programs and in what follows it will be assumed, for the sake of argument, that all your Fortran work will be stored in this location.

Accessing the Plato Integrated Development Environment (IDE)

In order to access Plato you should proceed as follows:

  1. Log on to the ITS Networked PC Service.
  2. Click Start > Programs > Programming Languages > Salford Software > Fortran > Salford Plato IDE

Basic operation of the Plato IDE

In order to begin entering a program click on File followed by New – you will then be presented with a blank edit window in which you can begin typing in a program. Type, for example, the following program into the blank edit window:

program himum

write(*,*)’ hi mum !’

end program himum

Saving and compiling your program

At this stage, although you have entered your program into the Plato edit window the program has not yet been written to disk. Until this is done compilation cannot be carried out.

To save a copy of your program to disk click on File followed by Save As… and then enter the name of the file, himum.f95 in the J:\fortran folder. Note that all of your Fortran files must have a .f95 extension or they will not be recognised as Fortran programs and hence cannot be compiled.

The program will not actually be written to disk until you click Save

After clicking on Save you should notice that Plato, knowing that this file now contains a Fortran program, has highlighted some of the items in your program in bold type e.g. the words program, implicit, integer etc. You should also see that the character string ’ hi mum !’ has been highlighted in green. Later on, you will see that comments within your program will be highlighted in purple. This highlighting is automatically provided by Plato as an aid to program development.

Having saved himum you can now attempt to compile it by clicking on Project followed by Compile File.

Assuming that compilation was successful you have now produced ahimum.obj object file which has also been written to disk, in the same folder as your program. (Plato will also have created a file called errorlog in order to store information regarding the compilation but you need not concern yourself with this.)

Building (linking) your program and running it

Once the object file has been created, you can‘build’ the final, executable form of your program by ‘linking’ your own program code with the necessary support routines (intrinsic Fortran functions, input/output routines etc). This is done by clicking on Project followed by Build File. If all has gone well you should see a window headed with the words Build Successful and an executable file, himum.exe, will have been created in your Fortran folder. (A file called himum.lst and another called slinklog will also have been created containing information used by Plato but you need not concern yourself with this.) The program can be run by clicking on Run in the Build Successful window.

1.Fundamentals of Fortran Programming

1.1Basic Structure of a Fortran program

An example of a non-trivial Fortran 95 program can be found in the Appendix B, at the end of these notes. You are not expected to be able to make much sense of it at this stage if you have never studied Fortran before. However, have a brief look at it now, and note its general structure, which is typical of a Fortran program:

  1. Program name: Apart for a few lines of comments at the very beginning, the first line of the program is a ‘program statement’, program hgen, which defines the name of the program.
  2. Declaration of variables/data initialisation: A certain number of names (e.g., nt, nstep, …, integralz) are declared as being names of ‘variables’, for later use.
  3. Main program body containing executable statements: Here starts with an open statement.
  4. Subprogram(s): Here subroutine subprograms, starting with a subroutine statement.

Let us look at these a little more in detail:

1)Program name– in principle this item is optional but during this course you will always be expected to give a name to your programs e.g.

program fred1

The purpose of this is simply to enable you to recognise the program with which you are dealing by looking at the source program name. The source program is just the version of the program which you have typed into the computer (for those who are interested this will be in a standard ASCII file). Later versions may be called, for example:

program fred2

or

program fred3

etc.

2)Variables are used to store values in your program. In Fortran there areseveral pre-defined variable types e.g. integer, real and character which you will meet later. You should declare all such variables at the beginning of your program. Initial values can be assigned to variables by making use of data initialisation.

3)The main program body contains the executable Fortran statements which carry out the actual program. In many cases the appearance and efficiency of the main program can be aided by the use of subprograms.

4)Subprograms. Some programs use the same piece of lengthy code many times to carry out a particular task. To tidy up the main program and to keep the structure as simple as possible, these pieces of code can be relegated to subprograms, which are written in another location but can be ‘called’ as many times as necessary.

1.2The Fortran statement

As you can see from the example, a Fortran program consists of executable and non-executable statements put together in order to carry out a specified task, and of comments: Executable statementstell the computer to perform a particular operation e.g. the addition of two numbers. Non-executable statements provide information which enables the proper operation of the program e.g. the definition of variable types (see below). Commentsprovide information for the programmer or whoever may read the program, to help understanding what the program does and how it is structured. Typically, each statement occupies a single line. However, if needs arise you may split a statement over several lines.

1.3Lines in Fortran

1)! Comments - If the first character on a line contains an exclamation mark character,!, then the line is a comment. You may enter anything you wish on the rest of the line as it will be ignored by the compiler (see later). Comments are very important and should be used to document the operation/function of your code, preferably as you go along. You will find these comments become very important later on in understanding the details of your program! (There are many examples of comments in the program of Appendix B.)

2)Length - It is advisable to use no more than 72 columns of text when writing your programs as this will maximise compatibility with earlier versions of Fortran and should also ensure that there will be no problems when sending a copy of your program to the printer.

3)Statement label - if an integer number from 1 to 99999 is the first thing to appear on a line (apart from spaces) then this is a statement label. The use of these is explained later. In most situations spaces may be freely inserted at any place in your program, but there must be no spaces between the digits of a statement label: statement label 99999 will not be properly recognised if written as 99 999. (There is one example of statement label in Appendix B. The label is 123.)

4)Continuing a line - if a line ends with an ampersand, &, then the following line is simply a continuation of this line. You may also indicate (this is essential on some occasions) the start of the body of the following line with an &. In practice, you should try to organise your program so that you do not have to use continuation lines as this makes your program easier to read. (There is one example of continuation line in Appendix B.)

5)It is possible to have multiple Fortran statements on a single line by using a semi-colon to separate each statement, but this feature must not be used in this course as it makes the program more difficult to read. (This feature is not used in Appendix B.)

1.4Fortran variables

Numbers can be represented in integer format or in floating point format. These two formats refer to the way in which the number is represented in the computer. Integers can be represented either in integer format or in floating point format, as most appropriate in the context. Non-integers must be represented in floating point format. An integer represented in integer format is just that, a sequence of digits without decimal point. A number represented in floating format is defined by a mantissa and an exponent, as shown below:

Besides numbers, Fortran also offers the possibility of defining variables holding characters (either single characters or strings of characters ) or logical values (true or false).

The main variable types:

integer / Integers are stored in 4 bytes or 32 bits (that is 32 binary 0's and 1's) of storage space.This allows 232 integers between-2147483648 and +2147483647 to be represented.
real / Standard floating-point real numbers also have astorage allocation of 4 bytes. The sign, mantissa and exponent must all be held inthis storage space. The precise range depends onthe Fortran implementation but Salford Fortranholds real numbers between ~ +/- 10+/-38.The mantissa only has about 7 significant digits.
doubleprecision / Double precision floating point real numbers have twice the storage of 4-byte real’s andare thus allocated 8 bytes. This allows numbers between ~ +/- 10+/-308 to berepresented by Salford Fortran.The mantissa has about 16 significant digits.Double precision numbers should normally be used in preference to ‘standard’ real numbers whennumerical precision is important.
character(len=n) / Character variables can be used to hold standardtext/ASCII characters with one byte per characterand n bytes in total where n is an integer. If (len=n)is omitted the variable holds only 1 character.
logical / 4-byte variable with logical value .true. or .false.
complex / Two real (4-byte) numbers stored as a pairand treated as the real and imaginary partsof a complex number. The use this type of variables is explained in Chapter 6.

Rules for variable names

The names of the variables are not completely arbitrary. They

  • may contain alphabetic characters, numeric characters and the underscore character (_);
  • must begin with an alphabetic character; and
  • must be no longer than 31 characters in total.

It is useful to try to pick sensible variable names where possible to help you identify them later, but you will also use a number of ‘trivial’ variables for which this makes little sense. You should also try not to use names which are too long –you will probably have to type them in a number of times and the more characters they contain the more likely you are to make a mistake.

Unlike some other programming languages Fortran does not distinguish between upper and lower case characters. Thus a variable called NUMBERis entirely equivalent to one called number or NUMber, etc.

By default, Fortran assumes that any undeclared variables with names beginning with the characters i,j,k,l, m or n are of type integer whereas all others (a to h and o to z) are of type real. You are strongly advised to comply with this convention when naming variables during this course, even though you have been told to use only declared variables (which over-rules the default convention). This may be useful, particularly to the demonstrators, in the event (as will surely happen) that you encounter problems when running your programs.