Multi Dimensional Arrays in COBOL

Multi dimensional arrays in COBOL are supported and it is possible to have up to 7 dimensions which is its MAX limit. But more than two dimension array creates confusion.So in general two dimensional arrays and Single dimensional arrays are used mostly. Let us see how to declare and process multi dimensional arrays in COBOL.

As we know, Array is nothing but the set of similar data elements stored together. Days that are in a week is an Array.

EX:
01 WS-WEEK-ARRAY.
05 WS-WEEK-DAY OCCURS 7 TIMES.

This is Single dimensional Array where it can be accesses using either index or Subscript.
WS-WEEK-DAY(1) can be used to access the first day of the week array. It is quite simpler. But more dimensions needs more care while accessing it.

Declaration:
If I want an array of Students with their marks in each subject.Say there are 30 students in a class and 6 Subjects. So this can be declared as below.

Accessing:

Declaration can be done as shown above, but while accessing the data in two dimensional arrays care must be taken.For example if I want to display all the Students along with the subjects and Marks, how this can be achieved.

Sample code: In this sample code, first I becomes 1 and for each value of I, J iterates 6 times thus for each student 6 Subjects & marks gets displayed. WW-SUB(1,1), WW-SUB(1,2), WW-SUB(2,1),WW-SUB(2,2) etc..

Instead of Using two perform statements, this can be achieved in a single Perform statement by usng an AFTER verb.

Note: AFTER works ONLY with Paragraphs. We can not use after with the above example.

Initializing the two Dimensional Arrays:

INITIALIZE verb can be used on the top level item which replaces all the Alphanumeric items with spaces and Numeric items with zeroes.

If we want to initialize the lower table data only, i.e. Subject and Marks needs to be wiped out and Student name should be there. In this case we can not code as below because table items can not be initialized without using indexes or subscripts.

This can be done as below:

If using performs for Initialize seems involving more code, then modify the array declaration as below and use simple Initialize verb.

Leave a Reply

Your email address will not be published. Required fields are marked *