How to use an array in Cobol
In COBOL, the OCCURS
clause can be used to define a table (array). In the
example, a table WS-NUM-TABLE
with 10 elements is created. Each element
(NUM-ITEM
) is of type PIC 9(4)
and can store a number up to 9999. Using the
PERFORM VARYING
loop, the array is filled starting with WS-INDEX
. The loop
assigns a value to each element in the table (here, from 1 to 10).
IDENTIFICATION DIVISION.
PROGRAM-ID. array.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-INDEX PIC 9(02) VALUE 1.
* Array with 10 numbers
01 WS-NUM-TABLE.
05 NUM-ITEM PIC 9(4) OCCURS 10 TIMES.
PROCEDURE DIVISION.
MAIN-PROGRAM.
DISPLAY "Fill array with values 1 to 10".
PERFORM VARYING WS-INDEX FROM 1 BY 1 UNTIL WS-INDEX > 10
MOVE WS-INDEX TO NUM-ITEM(WS-INDEX)
END-PERFORM
DISPLAY "Content off Array:".
PERFORM VARYING WS-INDEX FROM 1 BY 1 UNTIL WS-INDEX > 10
DISPLAY "Array Value " WS-INDEX ": " NUM-ITEM(WS-INDEX)
END-PERFORM
STOP RUN.