Subarrays 


Choosing the size of an array is not always easy.  The number of locations for an array must be known in advance, but since the exact number of locations to be used is often dependent on the data, a safe maximum number must be chosen to use in the declaration of the array.  As values are actually stored in the array, a count can be kept of how many locations are actually used.  This count is used to insure that only locations in which data is stored are processed.  The getUpperBound method is not sufficient for this purpose--it returns the maximum index in the array rather than the number of elements in use.

In light of this discussion, it is apparent that we often want to process only a portion of an array, or a subarray.

For example, if a course array is declared to have the same number of elements as the course limit specified by the department (the maximum possible size) then it is likely that the actual number of students, and hence the number of data elements used, will actually be smaller for a variety of reasons.  In order to process grades the algorithm should access only those elements that are used.  If the number of elements is associated with the array then it is an easy matter to process from 0 to number of elements.  If number of elements was not stored as elements were added to the array, then a function must be written to determine the number of elements in use.  One possibility follows:

Subs and functions that have array parameters should also be passed a elementsUsed parameter that tells how many of the locations have values in them to be processed.