FORTRAN Logical expressions

Home Computational Physics FORTRAN FORTRAN Logical expressions

Transfer of control

Some times we want to execute statements in some order other than the normal one-after-the-other sequence. Sometimes we shall return to the beginning of the program to execute it again with different data, or we may branch around a section of the program, depending on the values of computed intermediate results.

In this section we shall explore the FORTRAN language elements available for masking transfers of control, and we shall also look into a number of examples that illustrate the use of these language elements and of computers generally.

Logical expressions
Logical expressions can only have the value .TRUE. or .FALSE.. A logical expression can be formed by comparing arithmetic expressions using the following

Relational operators.
Relational operators
Relational OperatorMeaning
.LT.Less than
.LE.Less than or equal to
.EQ.Equal to
.NE.Not equal to
.GT.Greater than
.GE.Greater than or equal to

Note : So you cannot use symbols like < or =, but you have to use the correct two-letter abbreviation enclosed by dots!

Logical expressions can be combined by the logical operators .AND. .OR. .NOT. which have the obvious meaning.

The IF statements
An important part of any programming language are the conditional statements. The most common such statement in Fortran is the IF statement, which actually has several forms. The simplest one is the logical if statement:

IF (logical expression) executable statement

This has to be written on one line. This example finds the absolute value of x:

IF (X .LT. 0) X = -X

If more than one statement should be executed inside the if, then the following syntax should be used:
IF (logical expression) THEN

The most general form of the if statement has the following form:
IF (logical expression) THEN
ELSEIF (logical expression) THEN
The execution flow is from top to bottom. The conditional expressions are evaluated in sequence until one is found to be true. Then the associated code is executed and the control jumps to the next statement after the ENDIF.

Nested if statements
IF statements can be nested in several levels. To ensure readability, it is important to use proper indentation. Here is an example:
IF (X .GT. 0) THEN
WRITE(6,*) 'X is positive and X >= Y'
WRITE(6,*) 'X is positive but X < Y'
WRITE(6,*) 'X is negative'
WRITE(6,*) 'X is zero'

You should avoid nesting many levels of if statements since things get hard to follow.