FORTRAN 90+: IF-THEN-ELSE
The IF-THEN-ELSE conditional statements are used to control the program to perform certain operations depending on the value of one or multiple variables. Once an IF is .TRUE. the code skips any following ELSE or ELSE IF statements.
The simplest example is the IF statement. Here, the general format is
IF (true or false statement) arithmetic operation
For example, if a > c, then set a = b. This would appear as
IF (a > c) a = b
If a is less than or equal to c, then no operation is performed. Only one arithmetic operation can be performed per simple IF statement.
A more powerful tool is the block IF-THEN-ELSE set of statements. Its general format is
IF (true or false statement) THEN Code to do if .TRUE. ELSE Code to do if .FALSE. END IF
END IF can appear as two words or as one word, ENDIF, depending on the programmer’s fancy.
The block IF statement can be used in place of the simple IF statement:
IF (a > c) THEN a = b ENDIF
Additional statements can be added here as well:
IF (a > c) THEN a = b WRITE(*,*) ’a is greater than c’ ENDIF
Good programming practice is to indent the operations within the block IF for readability. In addition, using capital letters for the intrinsic operations and small letters for the programmer’s operations makes for easier reading.
Multiple true or false questions to give the program more options other than the two allowed in the above example can be accomplished using one of two possible procedures.
-
Nesting can be used to produce multiple true false questions as well as to make multiple options for a .TRUE. answer. Nesting is when IF statements reside within other IF statements. Using partial pseudo-code this is illustrated as
IF (a > b) THEN IF (a > c) THEN output= ’Arnold wins’ ELSE output= ’Chad wins’ END IF ELSE IF (b>c) THEN output= ’Bobby wins’ ELSE output= ’Chad wins’ END IF END IF
-
Nesting can get messy very quickly so a better method may be to use the ELSE IF command. This statements tells the computer to check a series of questions looking for the first .TRUE. statement. The code above could be written as follows using ELSE IFs.
IF (a > b .AND. a > c) THEN output= ’Arnold wins’ ELSE IF (b > a .AND. b > c) THEN output= ’Bobby wins’ ELSE output= ’Chad wins’ END IF
ELSE IF (or ELSEIF) statements must come before any ELSE statements, and only one END IF statement is needed for the entire block.
For long block IF statements, it is good programming practice to name it. The name assigned to the statement is stated at the beginning and end of the block statement and the name must be identical. The example above can be named as ’winner’:
winner: IF (a > b .AND. a > c) THEN output= ’Arnold wins’ ELSE IF (b > a .AND. b > c) THEN output= ’Bobby wins’ ELSE output= ’Chad wins’ END IF winner
IF-THEN statements are generally very intuitive but are also quite useful. A useful programming tip is to write down and check the logical statements for complex problems prior to programming them.