Nested IF
Part of the Decisions and Loops section of Coddy's COBOL Programming journey. Lesson 3 of 20.
An IF can sit inside a branch of another IF. Each IF gets its own END-IF:
IF ACCT-TYPE = "S"
IF BALANCE >= 1000
DISPLAY "Interest 2"
ELSE
DISPLAY "Interest 1"
END-IF
ELSE
DISPLAY "No interest"
END-IF.An ELSE belongs to the nearest IF that has no ELSE yet, and an END-IF closes the nearest open IF. Indent each level so a reader sees the pairing the compiler uses.
A chain of checks puts the next IF in the ELSE branch, and closes each IF at the end:
IF SCORE >= 90
DISPLAY "A"
ELSE
IF SCORE >= 75
DISPLAY "B"
ELSE
DISPLAY "C"
END-IF
END-IF.Two or three levels are as deep as a reader can follow. A longer chain reads better as an EVALUATE, which comes in the next chapter.
Challenge
EasyRead AGE and HAS-TICKET. Print Too young under 18. From 18 on, print Enter when HAS-TICKET is Y and Buy a ticket otherwise.
Example input, one line per ACCEPT: 30, Y.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. TICKET.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 AGE PIC 999.
01 HAS-TICKET PIC X.
PROCEDURE DIVISION.
ACCEPT AGE.
ACCEPT HAS-TICKET.
*> Check the age, then the ticket
STOP RUN.