Arrays


An array is a series of repeating data elements. The individual elements of an array are referenced within programs by appending a subscript to, depending on the programming language, either the array name or the element name.

The following Cobol code specifies an array having 10 elements of 5 bytes each. The total size of the array is 50 bytes.


01 MY-ARRAY.
   02 MY-ELEMENT OCCURS 10 TIMES PIC X(5).

In the above example MY-ELEMENT (7) would be the notation to reference the seventh element of the array. (7) is the subscript.

In the next example an array of ten elements is specified. Each element of the array consists of 9 bytes each.


01 ZIP-CODE-ARRAY.
   02 ZIP-CODE OCCURS 10 TIMES.
      03 ZIP-CODE-DIGITS PIC X(5).
      03 ZIP-PLUS-FOUR   PIC X(4).

In the above example ZIP-CODE (1) would be the notation to indicate the first nine-digit zip code stored in the array. If we only wanted to reference the first five digits of that first zip code, we would use the notation ZIP-CODE-DIGITS (1).

An array may have more than one dimension. In the following example we have created a two dimensional array of course registrations. We assume this array is part of each student's transcript record.


01 REGISTRATION-ARRAY.
   02 ACADEMIC-SEMESTER OCCURS 20 TIMES.
      03 COURSE-TAKEN OCCURS 10 TIMES.
         04 COURSE-ID-NUM PIC X(6).
         04 FINAL-GRADE PIC X.

In the above example we allow for a maximum of twenty semesters per student. Within each semester we allow for the student to be registered for a maximum of ten courses.

Sizing of the array is critical because it is static. We cannot exceed the maximum limits imposed by the predefined array size. (e.g., We are unable to store an eleventh course for a student, or a twenty-first semester for a student.) On the other hand, the larger we make the array, the more we risk the waste of allocating storage space that will never be used.