Pular para o conteúdo principal
eLearner.app
Módulo 4 · Lição 2 de 28/10 no curso~15 min
Lições do módulo (2/2)

Tabelas e cláusula OCCURS

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

Exercício#cobol.m4.l2.e1
Tentativas: 0Carregando…

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

Carregando editor…
Mostrar dica

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

Solução disponível após 3 tentativas

Exercício#cobol.m4.l2.e2
Tentativas: 0Carregando…

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.

Carregando editor…
Mostrar dica

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

Solução disponível após 3 tentativas