Partially Filled Arrays

In this lesson, we will use an array that might be larger than needed for a particular set of data.

Example: Count the items in a data set

Earlier, we asked the user for the size of the input data set when we calculated the average and computed deviations. Suppose that our program, not the user, counts the items in the data set. For example, let’s read up to 50 positive integers, counting them and saving them in an array. As soon as we read an integer that is not positive, we will stop. Recall that the signal to stop—in this case, a zero or negative number—is called a sentinel.

Although we do not know exactly how many integers we will read, we can choose an upper limit on the number of integers we will allow the user to enter. Let’s choose 50 as our upper limit. Thus, we can create an array of 50 locations to accommodate the largest possible data set as follows:

public static final int CAPACITY = 50;
int[] data = new int[CAPACITY];

Get hands-on with 1200+ tech skills courses.