IF Statement
The IF statement is a conditional statement that evaluates the truth of a condition, and provides alternative branches for the runtime to follow depending on whether the condition is true or false.
General Format:
IF condition-1 [THEN] { statement-list-1 } …
[ ELSE {statement-list-2 } … ]
[ END-IF ]
Syntax:
condition-nis a condition name described in a level 88 statement.statement-list-nconsists of one or more imperative or conditional statements.
General Rules:
- If
condition-1isTRUE,statement-list-1executes, and control is then passed to the next executable statement. - If
condition-1isFALSE, and if anELSEclause exists, thenstatement-list-2executes. If noELSEclause exists, then control is transferred to the end of theIFstatement. - An
IFstatement can be terminated by:- A period “
.”. - An
END-IFstatement at the same nesting level. - An
ELSEphrase in anIFstatement at a higher nesting level.
- A period “
statement-list-2is optional. If there is no statement list following anELSEphrase, the end of the scope of theELSEstatement is reached, and control passes to a higher nesting level, or to the statement following theIFstatement.
Code Sample:
IDENTIFICATION DIVISION.
PROGRAM-ID. IF-1.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 NUMERIC-1 PIC9(5)V9(5) VALUE 10.
77 NUMERIC-2 PIC9(5)V9(5) VALUE 20.
77 DUMMY PIC X.
PROCEDURE DIVISION.
MAIN.
IF NUMERIC-1 > NUMERIC-2
THEN
DISPLAY "YOU WIN!" LINE 10 COL 10
ELSE
DISPLAY "YOU LOSE!" LINE 10 COL 10
DISPLAY "CHANGE VALUES AND TRY AGAIN." LINE 11 COL 10
END-IF.
ACCEPT DUMMY LINE 11 COL 40.
STOP RUN.