Tables: OCCURS arrays

OCCURS

OCCURS declares a table: one data item repeated a fixed number of times. The OCCURS clause sits on the repeating item, not on the group. SEARCH also needs an index register, so the table declares one with INDEXED BY:

01 WS-TEMPS. 05 WS-TEMP PIC S9(3) OCCURS 7 TIMES INDEXED BY WS-TEMP-IX.

Subscripts

Use a subscript in parentheses to read or write one entry. Subscripts are 1-based, unlike C arrays, and the compiler checks them against the table size at run time:

MOVE 72 TO WS-TEMP(1). MOVE WS-TEMP(3) TO WS-HIGH. DISPLAY "Day 3: " WS-TEMP(3).

SEARCH

SEARCH scans a table for the first match. It uses the index register you set with SET, and AT END runs when nothing matched:

SET WS-TEMP-IX TO 1. SEARCH WS-TEMP AT END DISPLAY "Not found" WHEN WS-TEMP(WS-TEMP-IX) = 72 DISPLAY "Found at " WS-TEMP-IX END-SEARCH.

The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev