DEV Community

Cover image for COBOL Tutorial Series: Condition (IF, ELSE) statement - Session 3
Duc Nguyen Thanh
Duc Nguyen Thanh

Posted on

COBOL Tutorial Series: Condition (IF, ELSE) statement - Session 3

Hello, I'm Duke

In the previous 2 sessions, I have guided you on how to develop, compile and create a simple calculation program using COBOL.

Now, I will systematize the knowledge of the previous two articles and explain more about COBOL syntax

1. Variable declaration

Data in COBOL is declared in the DATA DIVISION and variables are usually defined in the WORKING-STORAGE SECTION.

       IDENTIFICATION DIVISION.          
       PROGRAM-ID. SimpleVariable.       

       DATA DIVISION.                    
       WORKING-STORAGE SECTION.          
       01 WS-NAME PIC A(20) VALUE 'Duke'.
       01 WS-AGE  PIC 9(2) VALUE 32.     
       PROCEDURE DIVISION.               
       Main-Process.                     
           DISPLAY 'Name: ' WS-NAME.     
           DISPLAY 'Age: ' WS-AGE.       
           STOP RUN.                     
Enter fullscreen mode Exit fullscreen mode

Variable declaration

  • WS-NAME is a string variable of length 20 and default value is 'Duke'.
  • WS-AGE is a 2-digit integer variable with default value 32.
  • The program displays the declared name and age

2. Condition (IF..ELSE) statement

COBOL allows the use of IF ... ELSE statements to test conditions and control the flow of execution based on the test results.

       IDENTIFICATION DIVISION.                              
       PROGRAM-ID. LoginCheck.                               

       DATA DIVISION.                                        
       WORKING-STORAGE SECTION.                              
       01 WS-USERNAME PIC X(20).                             
       01 WS-PASSWORD PIC X(20).                             
       01 WS-STORED-USERNAME PIC X(20) VALUE 'Duke'.         
       01 WS-STORED-PASSWORD PIC X(20) VALUE 'HjhXhxw8-P]wY4;'.

       PROCEDURE DIVISION.                                   
       Main-Process.                                         
           DISPLAY 'Enter your username: '.                  
           ACCEPT WS-USERNAME.                               
           DISPLAY 'Enter your password: '.                  
           ACCEPT WS-PASSWORD.                               
           IF WS-USERNAME = WS-STORED-USERNAME AND           
              WS-PASSWORD = WS-STORED-PASSWORD               
               DISPLAY 'Login successful! Welcome, ' WS-USERNAME '!'
           ELSE                                    
               DISPLAY 'Invalid username or password!'.
           STOP RUN.
Enter fullscreen mode Exit fullscreen mode

and here is the result

Condition statement

Repository here

Top comments (0)