Docsity

Selective Execution - Mechanical Engineering - Lecture Slides, Slides of Mechanical Engineering

Partial preview of the text

Download Selective Execution - Mechanical Engineering - Lecture Slides and more Slides Mechanical Engineering in PDF only on Docsity!

MET 50

Fortran

SELECTIVE EXECUTION

MET 50

THE VERY WONDERFUL

“IF”

STATEMENT

Easiest version: IF (expression) (statement) Meaning: if the “expression” is true, the “statement” is executed. if the “expression” is false, the “statement” is not executed.

In this case: “statement” must be a single statement. Examples: IF (“X is larger than 5”) PRINT*,X IF (“TEMP negative”) TEMP = 9999. IF (“X is positive”) Y = SQRT(X)

The logical expression… X. GE. 0. can only have two values: TRUE or FALSE.

Thus with IF (X. GE. 0.) Y = SQRT(X) When X ≥ 0, we DO execute Y = SQRT(X) When X < 0, we do NOT execute Y = SQRT(X)

Next simplest version: IF (expression) THEN statements (usually multiple!) ENDIF (or can be END IF) Meaning: if the “expression” is true, the statements are executed.

Example: IMPLICIT NONE REAL :: A, B, C, QUANT, ANS READ, A, B, C QUANT = A2 – 4.BC IF (QUANT >= 0.) THEN ANS = SQRT(QUANT) PRINT,’RESULT IS’, ANS END IF

The logical expressions can be combined using: IF (QUANT >= 0. .AND. B > 4. ) THEN ANS = SQRT(QUANT) PRINT*,’RESULT IS’, ANS END IF F90 Meaning .AND. Both true .OR. One true .NOT. Nothing (?)

IF (QUANT >= 0. .OR. B > 4. ) THEN

ANS = SQRT(QUANT)

PRINT*,’RESULT IS’, ANS

END IF

IF (QUANT >= 0.) THEN ANS = SQRT(QUANT) PRINT,’ANSWER’,ANS ELSE PRINT,’REQUIRES SQRT(NEG NO)’ ENDIF

The IF – ELSEIF construct:

IF (expression1) THEN

statements

ELSE IF (expression2) THEN

statements

ELSE IF (expression3) THEN

statements

ENDIF

So the “IF” code structure is embedded in the program. There can be many of these! Can even have IF structures within IF structures! example…

IF (TEMP >= 90.) THEN

PRINT*,’IT IS HOT!’

IF (PRES > 1010.) THEN

PRINT*,’PRESSURE IS HIGH’

IF (HUM < 10.) THEN

PRINT*,’HUMIDITY UNDER 10%’

ENDIF

ENDIF

ENDIF

Note how we indent code to make segments easy to see and find.