跳转到主要内容
eLearner.app
模块 4 · 第 2 课(共 2)课程中的8/10~15 min
模块课程(2/2)

表和 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

锻炼#cobol.m4.l2.e1
尝试:0加载中...

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

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案

锻炼#cobol.m4.l2.e2
尝试:0加载中...

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.

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案