Arrays in COBOL
Our first example demonstrates the use of arrays in COBOL. In COBOL, an array is called a table and is a sequence of elements of a specific length.
IDENTIFICATION DIVISION.
PROGRAM-ID. ARRAYS-EXAMPLE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A-TABLE.
05 A OCCURS 5 TIMES PIC 9(3).
01 B-TABLE.
05 B OCCURS 5 TIMES PIC 9(3).
01 TWO-D-TABLE.
05 TWO-D OCCURS 2 TIMES.
10 TWO-D-INNER OCCURS 3 TIMES PIC 9(3).
01 I PIC 9(3).
01 J PIC 9(3).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM INITIALIZE-A
PERFORM DISPLAY-A
PERFORM SET-AND-GET-A
PERFORM INITIALIZE-B
PERFORM DISPLAY-B
PERFORM INITIALIZE-TWO-D
PERFORM DISPLAY-TWO-D
STOP RUN.
INITIALIZE-A.
MOVE 0 TO A(1)
MOVE 0 TO A(2)
MOVE 0 TO A(3)
MOVE 0 TO A(4)
MOVE 0 TO A(5).
DISPLAY-A.
DISPLAY "emp: " A-TABLE.
SET-AND-GET-A.
MOVE 100 TO A(5)
DISPLAY "set: " A-TABLE
DISPLAY "get: " A(5)
DISPLAY "len: 5".
INITIALIZE-B.
MOVE 1 TO B(1)
MOVE 2 TO B(2)
MOVE 3 TO B(3)
MOVE 4 TO B(4)
MOVE 5 TO B(5)
DISPLAY "dcl: " B-TABLE.
INITIALIZE-TWO-D.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 2
PERFORM VARYING J FROM 1 BY 1 UNTIL J > 3
COMPUTE TWO-D(I, J) = I + J - 2
END-PERFORM
END-PERFORM.
DISPLAY-TWO-D.
DISPLAY "2d: " TWO-D-TABLE.In this COBOL program:
We define a table
A-TABLEwith 5 elements, each capable of storing a 3-digit number.We initialize all elements of
A-TABLEto zero and display it.We set the 5th element of
A-TABLEto 100, then display the whole table and the 5th element individually.We initialize
B-TABLEwith values 1 through 5 and display it.We create a two-dimensional table
TWO-D-TABLEwith 2 rows and 3 columns, initialize it with values, and display it.
Note that COBOL doesn’t have a built-in function to get the length of a table, so we manually display the length of A-TABLE.
Also, COBOL doesn’t support dynamic array initialization like Go does. We have to explicitly set each value.
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 and environment.
$ cobc -x arrays-example.cob
$ ./arrays-example
emp: 000000000000000
set: 000000000000100
get: 100
len: 5
dcl: 001002003004005
2d: 000001002001002003This example demonstrates basic array (table) operations in COBOL, including initialization, setting and getting values, and working with multi-dimensional tables.