If Else in COBOL
Branching with IF
and ELSE
in COBOL is straightforward.
IDENTIFICATION DIVISION.
PROGRAM-ID. IF-ELSE-EXAMPLE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-NUM PIC 9(2).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
DISPLAY "IF/ELSE Example"
* Here's a basic example.
IF FUNCTION MOD(7, 2) = 0
DISPLAY "7 is even"
ELSE
DISPLAY "7 is odd"
END-IF
* You can have an IF statement without an ELSE.
IF FUNCTION MOD(8, 4) = 0
DISPLAY "8 is divisible by 4"
END-IF
* Logical operators like AND and OR are often useful in conditions.
IF FUNCTION MOD(8, 2) = 0 OR FUNCTION MOD(7, 2) = 0
DISPLAY "either 8 or 7 are even"
END-IF
* In COBOL, we can't declare variables within IF statements,
* so we'll set the variable before the IF.
MOVE 9 TO WS-NUM
IF WS-NUM < 0
DISPLAY WS-NUM " is negative"
ELSE IF WS-NUM < 10
DISPLAY WS-NUM " has 1 digit"
ELSE
DISPLAY WS-NUM " has multiple digits"
END-IF
STOP RUN.
To run the program, compile the COBOL code and execute the resulting program:
$ cobc -x if-else-example.cob
$ ./if-else-example
IF/ELSE Example
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that in COBOL, you need to use END-IF
to close each IF
statement. Also, COBOL doesn’t have a built-in modulus operator, so we use the FUNCTION MOD
to achieve the same result.
COBOL uses AND
and OR
for logical operations, which is more verbose but arguably more readable than symbols like &&
and ||
.
In COBOL, variable declarations are typically done in the WORKING-STORAGE SECTION
, and we can’t declare variables within control structures. Instead, we set the variable’s value before using it in the IF
statement.
COBOL doesn’t have a ternary operator, so you’ll need to use a full IF
statement even for basic conditions.