COBOL – IF ELSE ENDIF statement

Below sample COBOL program explains the IF ELSE END-IF statement. You can avoid using END-IF by using dot (‘.’) as scope terminator. But it is not a good practice. better, always code a END-IF statement as scope terminator.

‘THEN’ is optional. If you want, THEN you can use it.

----+----1----+----2----+----3----+----4----+----5----+----6----+----7--
       IDENTIFICATION DIVISION.           
       PROGRAM-ID.    KARTEST4.           
      * IF statement in cobol             
       ENVIRONMENT DIVISION.              
       DATA DIVISION.                     
       WORKING-STORAGE SECTION.           
        01 MY-NUMBER  PIC 9(2) VALUE 2.   
       PROCEDURE DIVISION.                
      * simple IF statement
           IF MY-NUMBER = 2               
              DISPLAY 'TWO'               
           END-IF                         
      * IF ELSE statement
           IF MY-NUMBER IS EQUAL TO 2 THEN
              DISPLAY 'TWO'               
           ELSE
              DISPLAY 'NOT TWO'
           END-IF              
      * nested IF ELSE statement
           IF MY-NUMBER = 1
              DISPLAY 'ONE'               
           ELSE
              IF MY-NUMBER = 2
                 DISPLAY 'TWO'
              ELSE
                 DISPLAY 'NEITHER ONE NOR TWO'
              END-IF
           END-IF              
           GOBACK.

Output of this program will be

TWO
TWO
TWO

Complete syntax of IF Command (COBOL)

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.