Menu
CoddyTech

OCCURS DEPENDING ON

Part of the Tables and Text section of Coddy's COBOL Programming journey. Lesson 8 of 19.

Some tables hold a different number of elements on each run. OCCURS DEPENDING ON gives a maximum and a field that says how many are in use:

01 N PIC 99 VALUE 0.
01 BASKET.
    05 BASKET-ITEM PIC X(3)
        OCCURS 1 TO 10 TIMES DEPENDING ON N.

The group's length follows N. With N at 2, BASKET is 6 characters, and DISPLAY BASKET prints the two elements in use and nothing after them.

SEARCH stops at element N, so the unused end of the table never matches.

Set N before using the table, and keep loops to N. GnuCOBOL checks a subscript against the maximum, 10, not against N: BASKET-ITEM(5) with N at 2 reads leftover storage without an error.

challenge icon

Challenge

Easy

BASKET always has room for 5 codes and prints all 5, even the empty ones. Make BASKET-ITEM occur 1 to 5 times depending on N, so 2, TEA, JAM prints [TEAJAM].

Example input, one line per ACCEPT: 2, TEA, JAM.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. BASKET.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 N PIC 9 VALUE 0.
       01 BASKET.
           05 BASKET-ITEM PIC X(3)
               OCCURS 5 TIMES.
       01 I PIC 9.
       PROCEDURE DIVISION.
           ACCEPT N.
           PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
               ACCEPT BASKET-ITEM(I)
           END-PERFORM.
           DISPLAY "[" BASKET "]".
           STOP RUN.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Tables and Text