Module lessons (2/2)
Decisions with IF and EVALUATE
Decision making in COBOL is performed primarily using the IF conditional statement and the multi-branch selection structure EVALUATE (analogous to switch or match in modern languages).
The IF Conditional Statement
The fundamental syntax of the IF statement is:
IF condition
statements-if-true
ELSE
statements-if-false
END-IF.
In modern COBOL versions (COBOL-85 and later), the statement must explicitly end with END-IF. instead of relying solely on the final period ., significantly reducing parsing and logic errors.
Common Conditions
- Greater than:
>orGREATER THAN - Less than:
<orLESS THAN - Equal to:
=orEQUAL TO - Greater than or equal to:
>=orGREATER THAN OR EQUAL TO - Less than or equal to:
<=orLESS THAN OR EQUAL TO
IF WS-BALANCE < 0
DISPLAY "OVERDRAWN"
ELSE
DISPLAY "ACCOUNT ACTIVE"
END-IF.
The EVALUATE Statement
When we need to compare a variable against multiple discrete values, nested IF statements can become complex. The EVALUATE statement resolves this by structuring the choices in a clean way:
EVALUATE WS-USER-ROLE
WHEN "ADMIN"
DISPLAY "FULL ACCESS"
WHEN "EDITOR"
DISPLAY "EDIT ACCESS"
WHEN OTHER
DISPLAY "LIMITED ACCESS"
END-EVALUATE.
WHEN OTHER: Identifies the fallback branch (equivalent todefaultor the finalelsein modern languages).END-EVALUATE.: Closes the structure.
Try it yourself
Write an IF-ELSE-END-IF block that checks if the variable WS-USER-AGE is greater than or equal to 18. If true, print 'ADULT', otherwise print 'MINOR' using DISPLAY.
Show hint
Use >= for the comparison, DISPLAY for output, and END-IF. (with the dot at the end of the block).
Solution available after 3 attempts
Complete the EVALUATE structure to check the WS-STATUS variable. If the value is 'A' print 'ACTIVE', if it is 'I' print 'INACTIVE', otherwise for any other value print 'UNKNOWN'.
Show hint
Write each WHEN branch followed by its DISPLAY, and use WHEN OTHER to handle the fallback.
Solution available after 3 attempts