Wednesday 19 August 2015

Difference between Subscript and Index


Subscript:
  • Represents number of occurrences of an array element.
  • It refers to the position of an array element where the element exists.
  • If it is single dimensional array, There is no need to declare this in data division because OCCURS clause automatically creates it.
  • Subscript value can be any positive integer and it always starts from 1.
  • Increment subscript refers to next occurrence of an array element.
  • In a one-dimensional table, the subscript corresponds to the row number and it is not required to declare in working storage section.
  • If it is multi dimensional array, a data item should be declared for subscript with S9(4) COMP.
Example:

01 WS-GROUP.
   05 WS-MONTH PIC X(3) OCCURS 12 TIMES.

To access second elements ws-month(2), for fourth ws-month(4) and so on...

Data item with OCCURS clause and without INDEXED BY can be accessed only by using subscript.

Index:
  • Number of displacement positions of an array.
  • Index should be declared by using INDEXED BY clause.
  • Index should be initialized to 1 by using SET operator before we use it.
  • Increment index by 1 increments the total length of single occurrence of an array.
  • Index should be incremented by SET <index-var> UP BY 1.
Example:
01 WS-GROUP.
   05 WS-MONTH PIC X(3) OCCURS 12 TIMES INDEXED BY WS-INDX.

To access second element, we need to first set the index to 2 like below

SET WS-INDX TO 2

Note : An index is similar to subscript, but internal values in the variables are different. Subscript refers to nonoccurence number of an element, for 2nd element it contains value 2
Index contains displacement from starting of an array, for 2nd element, it contains value 3(because array starts from 0, and 0,1,2 positions occupied by first occurrence and second occurrence starts from position 3). Similarly for 3rd occurrence, it contains value 6.

No comments:

Post a Comment