Chuyển đến nội dung chính
eLearner.app
Mô-đun 4 · Bài học 2 trong tổng số 28/10 trong khóa học~15 min
Bài học theo mô-đun (2/2)

Bảng và Điều khoản 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

tập thể dục#cobol.m4.l2.e1
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

tập thể dục#cobol.m4.l2.e2
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử