Arrays and loops

 

The idea of using a variable to hold the index into an array can be combined with loops to perform a multitude of useful operations on collections of data.  Suppose we’re interested in printing out the values of an array’s elements, our array numbers.   We can have a println statement for each array element as follows:

 

            System.out.println(numbers[0]);

      System.out.println(numbers[1]);

      System.out.println(numbers[2]);

            System.out.println(numbers[3]);

            System.out.println(numbers[4]);

 

It’s clear by looking at these statements that they only differ by the value of the index, while the operation of printing is repeated as many times as there are elements.  From our experience, repetitive code is what a loop is supposed to take care of.  We need to construct a loop that repeats as many times as there are elements in the array.  Let’s use as loop variable this i, which is initialized to 0.  For the loop to iterate 5 times, its final value must be 4, or more generally numbers.length-1.  Conveniently, the value of i at every loop iteration corresponds to the index of the element that we’d like to print.  The loop is doing the following:

 

            When i is          print out          

0                 numbers[0]

1                 numbers[1]

2                 numbers[2]

3                 numbers[3]

4                 numbers[4]

 

Putting this into code:

 

      int[] numbers = {2, 3, 6, 8, 11};

 

            for (int i = 0; i < numbers.length; i++)

            System.out.print(numbers[i] + “ “);

 

 

The value of numbers.length is 5, so the largest value of i for which the loop executes is 4. 

 

To appreciate how powerful the combination of loops and arrays can be, consider this code that prints out every other array element:

 

      int[] numbers = {2, 3, 6, 8, 11};

 

            for (int i = 0; i < numbers.length; i = i+2)

            System.out.print(numbers[i] + “ “);

 

The only difference is that here we increment the index by two instead of one (in boldface).   You can think of writing a loop that prints out array elements in reverse order (starting with the last element).  We’ll revisit this powerful array/loop mix at several instances later, but first let’s look at how we can create an array without initially specifying the values of its elements.