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 statements are executed and the control resumes after the endif.
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(*,*) 'x is positive and x >= y' else write(*,*) 'x is positive but x < y' endif elseif (x .LT. 0) then write(*,*) 'x is negative' else write(*,*) 'x is zero' endif
You should avoid nesting too many levels of if statements since things get hard to follow.
Copyright © 1995-7 by Stanford University. All rights reserved.
[ Index ]