Looping through Part of an ArrayΒΆ

You don’t have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (&&) on line 7 to make sure that the loop doesn’t go beyond the bounds of the array.

// private field
private int[ ] values = {3,8,-3, 2};

public void doubleFirstFive()
{

   for (int i = 0; i < values.length && i < 5; i++)
   {
      values[i] = values[i] * 2;
   }
}

You can even start in the middle and loop through the rest of the array. Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements?

// private field
private int[ ] values = {3,8,-3, 2};

public void doubleLastHalf()
{

   for (int i = values.length / 2; i < values.length; i++)
   {
      values[i] = values[i] * 2;
   }
}

7-5-1: Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()?

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

public void doubleLast()
{

   for (int i = a.length / 2; i < a.length; i++)
   {
      a[i] = a[i] * 2;
   }
}





7-5-2: Given the following values of a and the method mystery what will the values of a be after you execute: mystery()?

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

public void mystery()
{

   for (int i = 0; i < a.length/2; i+=2)
   {
      a[i] = a[i] * 2;
   }
}






Mixed up programs

7-5-3: The following program has the correct code to reverse the elements in an array, a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.



7-5-4: The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.