Flow Control

Flow control

Like other programming languages, Fortran offers constructs which allow the programer to control the flow of the program as required. Both conditional and looping constructs are available. If statements are used when a block of code should or should not be executed, depending on the evaluation of a logical expression. For example, suppose we have a variable, which if negative causes a message to be printed to the screen:

if (a .LT. 0) then
write (∗ ,∗) 'a is less than zero'
endif 

Now suppose we wish to extend the above and print a suitable message if a turns out to be zero or greater:

if (a .LT. 0) then
write (∗ ,∗) 'a is less than zero'
else
! a is not less than zero - it is zero or greater
write (*,*) 'a is zero or greater'
endif 

In the above example, the code inside the else block is executed only if the logical expression (a .LT. 0) is false. There may be at most one else statement in an if block. To evaluate a second logical expression in addition to (a .LT. 0) we use the elseif statement -- continuing the above example, suppose we wish to print a message if a is exactly equal to zero:

if (a .LT. 0) then
write (∗ ,∗) 'a is less than zero'
elseif (a .EQ. 0) then
! a is exactly equal to zero
write (*,*) 'a is equal to zero'
else
! a is definitely greater than zero
write (*,*) 'a is greater than zero'
endif

There may be any number of elseif statements in an if block, and thus any number of logical expressions can be evaluated.

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo