Computational
FORTRAN
FORTRAN if statements | FORTRAN if statements | |
| An important part of any programming language are the conditional statements. The most common such statement in Fortran is the ifstatement, which actually has several forms.
The simplest one is the logical ifstatement: 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(*,*) '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 many levels of if statements since things get hard to follow. |
| Main Menu |
|---|
| |