BudiBadu Logo
Samplebadu

COBOL by Example: Variables

COBOL 2002

Declaring, initializing, and modifying variables in the WORKING-STORAGE SECTION with level numbers, PIC clauses for data type and size, and VALUE clauses for initialization, understanding COBOL naming conventions with hyphens and descriptive identifiers, manipulating data using MOVE for assignment and arithmetic verbs like ADD, and working with automatic type conversion and padding for fixed-width fields.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. VARS-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  USER-AGE    PIC 99 VALUE 25.
       01  USER-NAME   PIC X(10) VALUE "Alice".
       
       PROCEDURE DIVISION.
           DISPLAY "Name: " USER-NAME.
           DISPLAY "Age: " USER-AGE.
           ADD 1 TO USER-AGE.
           DISPLAY "Next Year Age: " USER-AGE.
           STOP RUN.

Explanation

Variables in COBOL are strictly defined in the DATA DIVISION, specifically the WORKING-STORAGE SECTION for program-internal data. Each variable declaration consists of a level number, a variable name (identifier), a PIC clause defining its type and size, and an optional VALUE clause for initialization.

COBOL variable names are case-insensitive and can be up to 30 characters long. They can contain letters, numbers, and hyphens, but must not start or end with a hyphen. It is common practice to use descriptive names with hyphens, like EMPLOYEE-SALARY or TOTAL-COUNT.

Data manipulation is done via verbs in the Procedure Division. In this example, MOVE is used for assignment, while arithmetic is handled by ADD. COBOL handles type conversion automatically where possible, but trying to move non-numeric data into a numeric field will cause a runtime error.

Code Breakdown

6
01 USER-AGE PIC 99 VALUE 25. Declares a 2-digit number initialized to 25. If we didn't use VALUE, the initial content would be garbage (unpredictable).
7
01 USER-NAME PIC X(10) VALUE "Alice". Declares a 10-character string. Since "Alice" is only 5 letters, COBOL automatically pads the remaining 5 positions with spaces.
10
DISPLAY "Name: " USER-NAME. Prints "Name: Alice " (note the trailing spaces).
12
ADD 1 TO USER-AGE. This is the COBOL way of saying "USER-AGE = USER-AGE + 1". It modifies the variable in place.