Search code examples
arrayscobol

Confused with the declaration of 2D arrays in COBOL


So let's assume that I have a file which consists of 10 students with 3 fields: Name, Gender, Age. So, theoretically, I would want to create a 10 by 3 array.
But when it comes to COBOL, two-dimensional tables are created by this example:

01 WS-TABLE.
   05 WS-A OCCURS 10 TIMES.
      10 WS-B PIC A(10).
      10 WS-C OCCURS 5 TIMES.
         15 WS-D PIC X(6).

In this example, I can not understand what WS-B and WS-D are. If I want to create an array like the one I mentioned (10 by 3), how may I do so?

Thanks


Solution

  • First of all COBOL doesn't have arrays per-se it has tables. There is no way to make a 2-dimensional table. The example you have give is actually the closest you can get (a nested table). If I was faced with the problem you do (a field of 10 student with Name, Gender and Age) I would structure my data like this:

    01 WS-TABLE.
       05 WS-STUDENT OCCURS 10 TIMES.
          10 WS-NAME   PIC X(10).
          10 WS-GENDER PIC X.
          10 WS-AGE    PIC 9(3).
    

    In this example I would use a subscript to access the fields I have created for student. So this is what a loop to display them all would look like:

    PERFORM VARYING WS-X 
               FROM 1 BY 1
              UNTIL WS-X > 10
       DISPLAY "NAME: " WS-NAME(WS-X) " GENDER: " WS-GENDER(WS-X) " AGE: " WS-AGE(WS-X)
    END-PERFORM