BudiBadu Logo
Samplebadu

COBOL by Example: Tables

COBOL 2002

Defining fixed-size arrays called tables using the OCCURS clause with 1-based indexing, implementing variable-length tables with OCCURS DEPENDING ON clause, accessing table elements with parentheses notation, and creating multi-dimensional tables for matrices and complex data structures.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. TABLES-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  WEEK-TABLE.
           05  DAY-NAME    PIC X(10) OCCURS 7 TIMES.
       01  I               PIC 99.
       
       PROCEDURE DIVISION.
           MOVE "Monday"    TO DAY-NAME(1).
           MOVE "Tuesday"   TO DAY-NAME(2).
           MOVE "Wednesday" TO DAY-NAME(3).
           
           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 3
               DISPLAY "Day " I ": " DAY-NAME(I)
           END-PERFORM.
           STOP RUN.

Explanation

In COBOL, arrays are called Tables. They are defined using the OCCURS clause, which specifies how many times a data item repeats. Tables are strictly fixed-size; you must define the maximum number of elements at compile time (though modern COBOL supports dynamic allocation with OCCURS DEPENDING ON).

Tables are 1-indexed, meaning the first element is at index 1, not 0. You access elements using parentheses, e.g., DAY-NAME(1). You can iterate through tables using a PERFORM VARYING loop with a subscript variable.

COBOL tables can also be multi-dimensional. You can nest an OCCURS clause inside another group item that also has an OCCURS clause, allowing for matrices and complex data structures. Accessing these requires multiple subscripts, like MY-TABLE(ROW, COL).

Code Breakdown

7
OCCURS 7 TIMES. Defines an array of 7 elements. Each element is a 10-character string.
11
DAY-NAME(1). Accessing the first element. Note that COBOL uses parentheses for subscripts.
12
MOVE "Tuesday" TO DAY-NAME(2). Assigns a value to the second slot in the table.
15
PERFORM VARYING I... Loops through the table using 'I' as the index.
16
DISPLAY ... DAY-NAME(I). Uses the variable 'I' to access the current element dynamically.