Menu
CoddyTech

Subscripts

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

The number in brackets is a subscript. It can be a literal or a numeric field:

ACCEPT M.
DISPLAY MONTH-NAME(M).

Subscripts count from 1. MONTH-NAME(1) is the first element, and there is no element 0.

A subscript can add or take away a literal, to reach the next or the previous element:

DISPLAY MONTH-NAME(M + 1).

A subscript outside the table is a bug. These programs are compiled with checks on, so GnuCOBOL stops the program and says why:

error: subscript of 'MONTH-NAME' out of bounds: 13

Without checks, a mainframe program reads or overwrites the storage after the table, and can end in an ABEND such as S0C4.

When a subscript comes from input, check it before using it:

IF M >= 1 AND M <= 12
    DISPLAY MONTH-NAME(M)
END-IF.
challenge icon

Challenge

Easy

The program reads a month number from 1 to 11 into M. Display that month's name and the next one's from MONTH-NAME, with a space between: 7 prints Jul Aug.

Example input, one line per ACCEPT: 7.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. MONTH.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 MONTHS.
           05 MONTH-NAME PIC X(3) OCCURS 12 TIMES.
       01 M PIC 99.
       PROCEDURE DIVISION.
           MOVE "JanFebMarAprMayJunJulAugSepOctNovDec"
               TO MONTHS.
           ACCEPT M.
           *> Display month M and the next here
           STOP RUN.

All lessons in Tables and Text