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
statements
ENDIF

The most general form of the if statement has the following form:
IF (logical expression) THEN
statements
ELSEIF (logical expression) THEN
statements
:
:
ELSE
statements
ENDIF
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
IF (X .GE. Y) THEN
WRITE(6,*) 'X is positive and X >= Y'
ELSE
WRITE(6,*) 'X is positive but X < Y'
ENDIF
ELSEIF (X .LT. 0) THEN
WRITE(6,*) 'X is negative'
ELSE
WRITE(6,*) 'X is zero'
ENDIF

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