Variables in COBOL

In COBOL, variables are explicitly declared in the DATA DIVISION and used throughout the program. Here’s an example demonstrating variable declaration and usage:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. VARIABLES-EXAMPLE.
       
       ENVIRONMENT DIVISION.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 A PIC X(7) VALUE "initial".
       01 B PIC 9(4) VALUE 1.
       01 C PIC 9(4) VALUE 2.
       01 D PIC X VALUE 'T'.
       01 E PIC 9(4).
       01 F PIC X(5) VALUE "apple".
       
       PROCEDURE DIVISION.
           DISPLAY A
           DISPLAY B " " C
           IF D = 'T'
               DISPLAY "true"
           END-IF
           DISPLAY E
           DISPLAY F
           STOP RUN.

In COBOL, variables are declared in the DATA DIVISION, specifically in the WORKING-STORAGE SECTION for this example.

The PIC clause defines the type and size of the variable:

  • PIC X(7) declares a string of 7 characters.
  • PIC 9(4) declares a numeric field of 4 digits.
  • PIC X declares a single character.

The VALUE clause is used to initialize variables:

       01 A PIC X(7) VALUE "initial".

You can declare multiple variables, each on its own line:

       01 B PIC 9(4) VALUE 1.
       01 C PIC 9(4) VALUE 2.

COBOL will use the type specified in the PIC clause:

       01 D PIC X VALUE 'T'.

Variables declared without a corresponding initialization are automatically initialized. For numeric fields, the default is zero:

       01 E PIC 9(4).

To declare and initialize a variable in COBOL:

       01 F PIC X(5) VALUE "apple".

In the PROCEDURE DIVISION, we use the DISPLAY verb to output the values of our variables:

           DISPLAY A
           DISPLAY B " " C
           IF D = 'T'
               DISPLAY "true"
           END-IF
           DISPLAY E
           DISPLAY F

To run this COBOL program, you would typically compile it and then execute the resulting program. The exact commands may vary depending on your COBOL compiler, but it might look something like this:

$ cobc -x variables-example.cob
$ ./variables-example
initial
1 2
true
0000
apple

This demonstrates basic variable declaration and usage in COBOL. Remember that COBOL has a very different structure and syntax compared to more modern languages, but the concepts of variable declaration and initialization are still present.