Arrays in Cobol are called tables, and they are a bit odd. For example the following code creates a 1D table with 5 elements in it, each of type x(5), or rather a “string” of 5 ascii characters.
01 planets occurs 5 times.
03 swplanet pic x(5).
Accessing each of the strings is done using the construct planets(x)
, where x
is the index. This is basically equivalent to:
01 planets pic x(5) occurs 5 times.
To make the string elements easily accessible, the declaration can be modified to:
01 planets occurs 5 times.
03 swplanet pic x occurs 5 times.
Now planets
is still a 1D table, but is comprised of swplanet
, which is also a 1D table, so in reality swplanet
is a 2D table. For example if the data stored in planets
is:
Endor Jakku Naboo Jedha Yavin
Then planets(1)
is Endor
, planets(2)
is Jakku
, etc. Now swplanet(i,j)
will access the jth element of the ith row, e.g. the value of swplanet(2,1)
is J (from Jakku). The code below prints out the individual elements of the 2D table in a row.
perform varying i from 1 by 1 until i=6
perform varying j from 1 by 1 until j=6
display swplanet(i,j), " " with no advancing
end-perform
end-perform.
Here is the output (note without the “no advancing
“, each element would be output to a separate line):
E n d o r J a k k u N a b o o J e d h a Y a v i n
You can also associate indexes directly with a table (meaning they don’t need to be declared independently). For example:
01 planets occurs 5 times indexed by i.
03 swplanet pic x occurs 5 times indexed by j.
Now to change the indexes we need to use the set
statement. For example to read in the data from file, the code changes from:
move 1 to i.
perform with test before until feof='y'
read input-file
at end move 'y' to feof
not at end move planet-info to planets(i), add 1 to i
end-perform.
to:
set i to 1.
perform with test before until feof='y'
read input-file
at end move 'y' to feof
not at end move planet-info to planets(i), set i up by 1
end-perform.