Module 9: Array processing and Table handling
Two –dimensional Array
- We already know, COBOL-85 supports maximum of 7 dimensions
- When we define array with more than one dimension, it is called as multi-dimension array
- Number of OCCURS clause used throughout given hierarchy indicates number of dimension.
- For example:-
In DATA DIVISION,01 DEPARTMENT-TABLE. 05 DEPARTMENT OCCCURS 3 TIMES. 10 DEPT-NAME PIC X(20). 10 EMP-NAME PIC X(20) OCCURS 2 TIMES.Reference visual:- In above visual,
- DEPT-NAME is one dimensional
- EMP-NAME is two dimensional
- If you observe in above data declaration, EMP-NAME throughout its data declaration hierarchy has two OCCURS clauses which indicates it is two-dimensional array
- In above example, the array is having 3 departments and each department has a name and 2 employees.
- Subscripts separated by comma can be used to access elements of multi-dimensional array
- In contrast to above given example, EMP-NAME(2,1) means first employee of second department
- EMP-NAME is two dimensional array as each of 3 departments is itself an array having another array ‘EMP-NAME’ with two occurrences
- DEPT-NAME is a one-dimensional array
- Let’s consider one more example to understand how to decide dimension of any given data item:-
01 ARRAY-EXAMPLE. 05 WS-A PIC A(3) OCCURS 10 TIMES. 05 WS-B OCCURS 20 TIMES. 10 WS-C PIC 9(2). 10 WS-D OCCURS 5 TIMES. 15 WS-E PIC 9(2) OCCURS 2 TIMES. 15 WS-F PIC X(2).
- In above example, WS-A and WS-C are one dimensional array. WS-B and WS-D are group items and are one-dimensional and two-dimensional respectively. WS-F is two dimensional array. WS-E is three dimensional array
Processing elements of Array
Suppose we have data stored in our array table in below format
In DATA DIVISION,
01 DEPARTMENT-TABLE.
05 DEPARTMENT OCCCURS 3 TIMES.
10 DEPT-NAME PIC X(20).
10 EMP-NAME PIC X(20) OCCURS 2 TIMES.
Visually it will have data like:-
Reference visual:-
Values visual:-
In PROCUEDURE DIVISION, we can write below code to display each elements of above multi-dimensional table
PARA-0.
PERFORM PARA-1 THRU PARA-1-EXIT
VARYING DEPT-I FROM 1 BY 1
UNTIL DEPT-I > 3
AFTER VARYING DEPT-J 1 BY 1
UNTIL DEPT-J > 2.
STOP RUN.
PARA-1.
DISPLAY ‘DEPARTMENT: ’ DEPT-NAME(DEPT-I)
DISPLAY ‘EMP-NAME: ’ EMP-NAME(DEPT-I, DEPT-J)
PARA-1-EXIT.
EXIT.
SYSOUT display (output):-
DEPARTMENT: MANUFACURING
EMP-NAME: RAMESH
DEPARTMENT: MANUFACURING
EMP-NAME: AKSHAY
DEPARTMENT: QUALITY
EMP-NAME: STEVE
DEPARTMENT: QUALITY
EMP-NAME: JOY
DEPARTMENT: MARKETING
EMP-NAME: ASHWANI
DEPARTMENT: MARKETING
EMP-NAME: JEFF
You will be able to understand how the program has processed in above example by mapping reference visuals, values visuals and SYSOUT displays.