Self-Study Guide 2: Programming in Fortran 95 by Dr. Rachael Padman - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

9 Some more topics

This section can be skipped at a first reading.

9.1 The case statement and more about if

If you have several options to choose between in a program, you can use the case statement, which takes the form:

select case (expression)

   case(value1,value2)

.  

.

   case(value3)

.

   case default

.

.

end select

 

  • expression must be an expression which evaluates to an integer, character or logical value.
  • value1, value2, … must be possible values for the expression.
  • if the expression matches either of value1 or value2 then the code following the case statement listing that value is executed.
  • If no match is found, the code following the optional case default statement is executed.

A simple example is the use of a case statement to take action on user input to a program:

img45.png

The same outcome could have been achieved using an if clause as follows: if ( logical expression) then

if (logical expression) then

 …

else if (logical expression) then

 …

else if (logical expression) then

 …

 else

 …

 end if

  • Try writing the above case statement using this form of the if clause. Ask a demonstrator to check that it is correct.

 

9.2 Other forms of do loops

We have already met the do loop in which the number of times round the do loop we go is determined at the start:

[name:] do var = start, stop [,step]

  xxx

 end do [name]

There are two other forms of the do loop which are useful; one we have seen already in a example:

[name:] do while (logical expression)

  xxx

end do [name]

 

Here the loop is repeated while the logical expression evaluates to .true..

The final form of the do loop requires that you use an exit statement somewhere within it, as the do loop is set up to loop indefinitely:

[name:] do

  xxx

  need some test which will result in an exit

end do [name]

img46.png

You may also like...