Looping From Back to FrontΒΆ

You don’t have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. This can be handy when you are looping through a sorted array and want to find the index of the first number that is less than some given number as shown in the method getIndexFirstSmaller below. Notice that the method returns -1 if there is no number in the array that is smaller than the given number. Why does this work?

// private field
private int[ ] values = {-3, -2, 4, 16, 23, 55};

public int getIndexFirstSmaller(int compare)
{

   for (int i = values.length - 1; i >=0; i--)
   {
      if (values[i] < compare) return i;
   }
   return -1; // to show none found
}

7-4-1: Given the following code segment what will be returned when you execute: getIndexFirstSmaller(-13);

private int[ ] values = {-20, -15, 2, 8, 16, 33};

public int getIndexFirstSmaller(int compare)
{
   for (int i = values.length - 1; i >=0; i--)
   {
      if (values[i] < compare) return i;
   }
   return -1; // to show none found
}





7-4-2: Given the following code segment what will be returned when you execute: getIndexFirstSmaller(7);

private int[ ] values = {-20, -15, 2, 8, 16, 33};

public int getIndexFirstSmaller(int compare)
{
   for (int i = values.length; i >=0; i--)
   {
      if (values[i] < compare) return i;
   }
   return -1; // to show none found
}