Skip to main content
eLearner.app
Module 4 · Lesson 2 of 28/10 in the course~15 min
Module lessons (2/2)

Tables and OCCURS Clause

In COBOL, there is no "array" or "vector" keyword to define lists of homogeneous data. For this purpose, you use the OCCURS clause, which specifies how many times a variable or structure repeats in memory.

Defining a Table with OCCURS

The OCCURS clause is added to the declaration of a subordinate variable (for example, level 05 or higher) within a group structure (level 01):

Code
01 WS-SALES-DATA.
    05 WS-MONTHLY-SALES PIC 9(4) OCCURS 12 TIMES.

In this example, WS-MONTHLY-SALES is a table consisting of 12 numerical elements of 4 digits each. The memory allocated for this record will be exactly 12 * 4 = 48 characters.

Accessing Elements and Indexes

To access a specific element in a table, specify the index in parentheses immediately after the field name.

[!IMPORTANT] Unlike most modern languages that use 0-based indexing, COBOL uses 1-based indexing. The first element is at index 1, the second at index 2, and so on.

Code
MOVE 1500 TO WS-MONTHLY-SALES(1).
MOVE 2400 TO WS-MONTHLY-SALES(2).

Traversing a Table (Iteration)

To loop through the elements of a table, you can use the PERFORM VARYING statement or manage a counter manually in a PERFORM UNTIL loop:

Code
PERFORM UNTIL WS-INDEX > 12
    DISPLAY "Sales: " WS-MONTHLY-SALES(WS-INDEX)
    ADD 1 TO WS-INDEX
END-PERFORM.

Try it yourself

Exercise#cobol.m4.l2.e1
Attempts: 0Loading…

Declare a table of 5 decimal temperatures (3 integer digits and 1 decimal) under the WS-WEATHER-DATA group structure using the OCCURS clause.

Loading editor…
Show hint

Write: 05 WS-TEMPERATURE PIC 9(3)V9 OCCURS 5 TIMES.

Solution available after 3 attempts

Exercise#cobol.m4.l2.e2
Attempts: 0Loading…

Initialize the first three elements of the WS-MONTHLY-SALES table with the values 1200, 1500, and 1800 respectively using MOVE statements. Remember that COBOL indexes start from 1.

Loading editor…
Show hint

Use MOVE 1200 TO WS-MONTHLY-SALES(1). for the first element, then repeat for the second and third using indexes (2) and (3).

Solution available after 3 attempts