In this topic, we described about the below sections -
Index is the number of displacement positions. Index can be created by using the INDEXED BY phrase of the OCCURS clause and the same used to identify an index-name.Take the below memory representation diagram to understand better about index.
Let us use the below declaration, to understand better about index -
01 BTECH-1ST-YEAR. 03 SUBJECT-MARKS PIC 9(03) OCCURES 6 TIMES.
Total 6 subject marks can be accessed like - SUBJECT-MARKS (1), SUBJECT-MARKS (2), SUBJECT-MARKS (3), SUBJECT-MARKS (4), SUBJECT-MARKS (5) and SUBJECT-MARKS (6).
How the Index is declared?
Index is declared by using INDEX BY clause.No separate declaration required in a working-storage section. Normally Indexes are allocated in static memory that is associated with the program which contains the table. The index declaration for the above example is -
01 BTECH-1ST-YEAR. 03 SUBJECT-MARKS PIC 9(03) OCCURES 6 TIMES INDEXED BY MARKS-INDEX.
How the INDEX is initialized?
Initialize the index by using a SET, PERFORM VARYING, or SEARCH ALL statement. Without initializing, the results are unpredictable. The lowest possible index value is 1. The index initialization for the above example is -
SET MARKS-INDEX TO 1. PERFORM VARYING MARKS-INDEX FROM 1 BY 1 UNTIL MARKS-INDEX > 6. SEARCH BTECH-1ST-YEAR WHEN SUBJECT-MARKS (MARKS-INDEX) EQUAL 100 ... END-SEARCH.
How the INDEX is incremented/decremented?
To change the value, a PERFORM, SEARCH or SET statement can be used. The compiler calculates the index value as the occurrence number (subscript) minus 1, multiplied by the length of the table element.
The index value = (occurrence number - 1) * table length. Therefore, for the third occurrence of BTECH-1ST-YEAR, the binary value contained in MARKS-INDEX is (3 - 1) * 3, or 6. Incrementing index for the above example is -
SET MARKS-INDEX UP BY 1. PERFORM VARYING MARKS-INDEX FROM 1 BY 1 UNTIL MARKS-INDEX > 6. SEARCH ALL BTECH-1ST-YEAR VARYING MARKS-INDEX WHEN SUBJECT-MARKS (MARKS-INDEX) EQUAL 100 ... END-SEARCH.
Decrementing index for the above example is -
SET MARKS-INDEX DOWN BY 1. PERFORM VARYING MARKS-INDEX FROM 6 BY -1 UNTIL MARKS-INDEX < 0. SEARCH ALL BTECH-1ST-YEAR VARYING MARKS-INDEX WHEN SUBJECT-MARKS (MARKS-INDEX) EQUAL 100 ... END-SEARCH.
How the table accessed using index in program?
Array element can be accessed by using the index like below.
The student marks can be accessed using index for the above example is -
Possible Errors: -
If the index increased beyond the number of occurrences and tries to access the table item with the index, that causes the S0C4 Protection Exception. The same error occurred if the index is not initialized and trying to access the table element with uninitialized index.
Debug the program to verify the index value at the time of program abend.