BudiBadu Logo
Samplebadu

COBOL by Example: Conditions

COBOL 2002

Controlling program flow with conditional logic using IF-ELSE-END-IF structure for decision-making, implementing level 88 condition names as boolean flags associated with variables for readable code, understanding comparison operators and verbose syntax alternatives, preventing scope termination errors with proper END-IF usage instead of periods, and creating self-documenting code with meaningful condition names.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. CONDITIONS.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  SCORE       PIC 999 VALUE 85.
       01  PASSED      PIC X VALUE 'N'.
           88 IS-PASSED    VALUE 'Y'.
       
       PROCEDURE DIVISION.
           IF SCORE >= 50
               MOVE 'Y' TO PASSED
               DISPLAY "You passed!"
           ELSE
               DISPLAY "You failed."
           END-IF.
           
           IF IS-PASSED
               DISPLAY "Congratulations!"
           END-IF.
           STOP RUN.

Explanation

Conditional logic in COBOL uses the standard IF...ELSE...END-IF structure. The END-IF scope terminator is crucial in modern COBOL to prevent logic errors, especially when nesting conditions. Before COBOL-85, periods were used to terminate logic, which often led to subtle bugs if a period was misplaced.

This example also introduces Level 88 Condition Names. These are boolean flags associated with a parent variable. In the code, 88 IS-PASSED VALUE 'Y' is true whenever PASSED equals 'Y'. This allows you to write readable code like IF IS-PASSED instead of checking the variable's value directly.

Using condition names makes the code self-documenting and easier to maintain. Instead of scattering literal values like 'A', 'B', or 'C' throughout your procedure division, you define them once in the data division with meaningful names like ACCOUNT-ACTIVE or ORDER-SHIPPED.

Code Breakdown

7
88 IS-PASSED VALUE 'Y'. A condition name. It is NOT a storage variable but a logical state of the variable PASSED.
10
IF SCORE >= 50. Standard comparison. COBOL also supports verbose syntax like "IF SCORE IS GREATER THAN OR EQUAL TO 50".
11
MOVE 'Y' TO PASSED. Sets the flag. This implicitly sets the condition IS-PASSED to true.
13
ELSE. The alternative path if the condition is false.
15
END-IF. Closes the IF block. Always use this instead of relying on periods, which can be error-prone.
17
IF IS-PASSED. Uses the level 88 condition name for a cleaner, more readable check.