The Queen's University of Belfast
Parallel Computer Centre

[Next] [Previous] [Top]

6 Control statements


Fortran 90 has three main types of control construct:

Each construct may be `nested' one within another, and may be named in order to improve readability of a program.

6.1 Conditional statements

In everyday life we make decisions based on certain circumstances. For instance after listening to the weather forecast one might take an umbrella. The decision to take an umbrella depends on whether it is raining or not. Similarly, a program must be able to select an appropriate action according to arising circumstances. For instance, to take different actions based on experimental results.

6.1.1 Flow control

Selection and routing control through the appropriate path of the program is a very powerful and useful operation. Fortran90 provides two mechanisms which enable the programmer to select alternative action(s) depending on the outcome of a (logical) condition.

6.1.2 IF statement and construct

The simplest form of the IF statement is a single action based on a single condition:

IF( expression ) statement

Only if expression (a logical variable or expression) has the value .TRUE. is statement executed. For example:

IF( x<0.0 ) x=0.0

Here, if x is less than zero then it is given a new value, otherwise x retains it's previous value. The IF statement is analogous to phrases like `if it is raining, take an umbrella'.

The structure of an IF construct depends on the number of conditions to be checked, and has the following general form:

[name:] IF (expression1) THEN

block1

ELSEIF (expression2) THEN [name]

block2

...

[ELSE [name]

block]

ENDIF [name]

Where expression# is a logical variable or expression.

The construct is used when a number of statements depend on the same condition. For example, `if it rains then phone for a taxi and take an umbrella'. This time the `then' part is required. Notice that an END IF (or ENDIF) part is required to indicate the end of the selection process. If it is raining the block of actions are executed and control passes to the next statement after END IF, otherwise the block of actions are skipped and control passes to the next statement after END IF.

A more complex situation is when one wants to perform alternative actions depending on the condition. For instance, both previous examples do not tell us what to do when it is not raining. The rules above can now be rephrased as: if it rains then phone taxi and take umbrella else walk.

Notice the use of the else part. The action-block parts may contain a single or more actions. The else part covers every other eventuality: sunshine, snowing etc. The passing of control follows the same rules as mentioned above.

There are situations though that alternative actions have to be taken depending on the value the condition takes. For instance, one might want to perform different action if it rains or snows or the sun is out. For example, if it is raining then phone taxi, take umbrella, else if it is snowing then stay at home, else if the sun is out then go to park, else walk. Notice the use of the ELSEIF part. The ELSE part acts as a default again in order to cover other eventualities. The same rules concerning passing of control apply.

The form can be used in a number of ways. For instance, multiple ELSEIFs can appear and/or the ELSE branch can be omitted and/or more IF constructs might follow ELSEIF or ELSE.

IF constructs can be labelled. Naming constructs can be useful when one is nested inside another, this kind of labelling makes a program easier to understand, for example:

outer: IF( x,0.0 ) THEN

...

ELSE outer

inner: IF( y<0.0 ) THEN

...

ENDIF inner

ENDIF outer

6.1.3 SELECT CASE construct

The SELECT CASE construct provides an alternative to a series of repeated IF ... THEN ... ELSE IF statements. The general form is:

[name:] SELECT CASE( expression )

CASE( value ) [name]

block

...

[CASE DEFAULT

block]

END SELECT [name]

The result of expression may be of type character, logical or integer; value must be of the same type as the result of expression and can be any combination of:

CASE DEFAULT is optional and covers all other possible values of the expression not already covered by other CASE statements.

For example:

INTEGER :: month

season: SELECT CASE( month )

CASE(4,5)

WRITE(*,*) `Spring'

CASE(6,7)

WRITE(*,*) `Summer'

CASE(8:10)

WRITE(*,*) `Autumn'

CASE(11,1:3,12)

WRITE(*,*) `Winter'

CASE DEFAULT

WRITE(*,*) `not a month'

END SELCET season

The above example prints a season associated with a given month. If the value of the integer month is not in the range 1-12 the default case applies and the error message `not a month' is printed, otherwise one of the CASE statements applies. Notice that there is no preferred order of values in a CASE statement.

6.1.4 GOTO

The GOTO statement can be used to transfer control to another statement, it has the form:

GOTO label

The GOTO statement simply transfers control to the statement with the corresponding label. For example:

...

IF( x<10 ) GOTO 10

...

10 STOP

The GOTO statement should be avoided where ever possible, programs containing such statements are notoriously hard to follow and maintain.

6.2 Repetition

An important feature of any programming language is the ability to repeat a block of statements. For example, converting a character from upper to lower case (or visa versa) can be done in a single executable statement. In order to convert several characters (in say a word or sentence) one has to either repeat the statement or re-execute the program. Using the repetition (or iteration) construct it is possible to restructure the program to repeat the same statement and convert the required number of characters.

6.2.1 DO construct

In Fortran 90 it is the DO loop (or construct) which enables the programmer to repeat a a block of statements. The DO construct has the general form:

[name:] DO [control clause]

block

END DO [name]

The DO construct may take two forms:

A count controlled loop uses a control clause to repeat a block of statements a predefined number of times:

[name:] DO count = start, stop [,step]

block

END DO [name]

The control clause is made up of the following:

On entering the loop count will take the value start, the second time round (after executing the statements in block) count will have the value start+step (or start+1 if step is missing) and so on until the last iteration when it will take the value finish (or an integer value no greater than stop). The number of times the statements will be executed can be calculated from:

If stop is smaller than start and step is positive then count will take the value zero and the statement(s) will not be executed at all. The value of count is not allowed to change within the loop.

For example:

all: DO i=1,10

WRITE(6,*) i !write numbers 1 to 10

END DO all

even: DO j=10,2,-2

WRITE(6,*) j !write even numbers 10,8,6,4,2

END DO even

In the absence of a control clause the block of statements is repeated indefinitely.

[name:] DO

block

END DO [name]

The block of statements will be repeated forever, or at least until somebody stops the program. In order to terminate this type of loop the programmer must explicitly transfer control to a statement outside the loop.

6.2.2 Transferring Control

The EXIT statement is a useful facility for transferring control outside the DO loop before the END DO is reached or the final iteration is completed. After an EXIT statement has been executed control is passed to the first statement after the loop.

The CYCLE statement is transferring control back to the beginning of the loop to allow the next iteration of the loop to begin.

Confusion can arise from multiple and nested (i.e. one inside another) DO loops, EXIT and CYCLE statements hence naming loops is highly recommended. As an example consider the following program:

PROGRAM averscore

REAL :: mark, average

INTEGER:: stid, loop

mainloop: DO

WRITE(*,*) 'Please give student id'

READ(*,*) stid

IF (stid==0) EXIT mainloop

average=0

innerloop: DO loop=1,3

WRITE(*,*) 'Please enter mark'

READ(*,*) mark

IF (mark==0) CYCLE innerloop

negs: IF (mark<0) THEN

WRITE(*,*) 'Wrong mark. Start again'

CYCLE mainloop

END IF negs

average=(average+mark)

END DO innerloop

average=(average)/5

WRITE(*,*) 'Average of student',stid,' is = ',average

END DO mainloop

END PROGRAM averscore

This program calculates the average mark of student given a series of 3 marks. It terminates when the user enters zero as the student id. In the case of a negative mark being entered the user has to re-enter all marks of that particular student (not only the wrong one!). In case of a zero mark the program asks for the next mark and saves adding a zero to the average total.

Notice that the labelling of DO and IF statements make the program not only easier to read and understand but more importantly able to perform the desired actions. Using EXIT or CYCLE without labels it would had made it difficult to comprehend which loop is referred to. Consider the case when the statement Cycle MainLoop was stripped from its label. The program thinks we refer to the InnerLoop and for every negative number we enter we miss a valid mark. Entering the following marks: 2 2 2 2 -4 results in an average of 1.6. The last value (-4) forces the program to go to the closest DO loop and to increase the counter. The counter then becomes five and the loop exits. So the logic of the program has been altered. If labels are not used then Exit will transfer control to the first statement after the END DO associated with the closest to Exit DO.

Similarly, Cycle will transfer control to the closest DO loop.This is a possible execution of the program:

6.3 Exercises

  1. Predict the values loop takes and the value loop has after termination of each of the following DO constructs, predictions may be tested by writing a program which accepts the values used in the loop control clause as input.

    (a) DO loop=5, 3, 1

    (b) DO loop=-6, 0

    (c) DO loop=-6, 0, -1

    (d) DO loop=-6, 0, 1

    (e) DO loop=6, 0, 1

    (f) DO loop=6, 0, -1

    (g) DO loop=-10, -5, -3

    (h) DO loop=-10, -5, 3

  2. Write a program which prints a multiplication table (i.e. 1n=?, 2n=?,... 12n=?). Allow the user to determine which table (value of n) they require.

  3. Write a program called `papersize' to calculate and display the size of A0 to A6 papers in mm and inches. Use following formula:

    Where n is the size of the paper 0 to 6, and one inch=2.54cm.

  4. Write a program to produce the Fibonacci sequence. This sequence starts with two integers, 1 and 1. The next number in the sequence is found by adding the previous two numbers; for example, the 4th number in the series is the sum of the 2nd and the 3rd and so on. Terminate when the nth value is greater than 100.

  5. The increase in temperature dT of a chemical reaction can be calculated using:

    where T is the temperature in centigrade, and t is the time in seconds. Write a program which prints the temperature of such a reaction at 1 minute intervals, The initial temperature is supplied by the user and the above equations should be re-calculated once every second. The program should terminate when the temperature reaches twice the initial temperature.


[Next] [Previous] [Top]
All documents are the responsibility of, and copyright, © their authors and do not represent the views of The Parallel Computer Centre, nor of The Queen's University of Belfast.
Maintained by Alan Rea, email A.Rea@qub.ac.uk
Generated with CERN WebMaker