Control Structures for Arrays#

The for-each loop is useful for processing one dimensional arrays, provided that a value in the array does not need to be changed. If a value does need to be changed, or work is with multiple arrays, then more control is needed, as given by the while loop. There are examples of each of these above: we used a for-each loop to print out a 1d array and we used a while loop when we needed to process two arrays simultaneously to check equality.

As dimensions are added to an array, loops will need to be nested – one loop for each dimension that we want to process. For example, notice the nested loop in the code to print a 2d array of integers, and also notice the data type for each element at each level of the loops:

/**
 * Displays a 2d integer array, one row per line.
 * @param intArray is a 2d array of integers
 */
 public static void print2dIntArray(int[][] intArray){
    for (int[] row : intArray){
       for (int item : row){
           System.out.print(item + " ");
       }
       System.out.println();
    }
 }//print2dIntArray

See how the outer for loop works on elements that are themselves an array of integers, that is, a row of the 2d array. The inner loop then handles the individual items in a row.

We could have used a nested while loop instead, and then our code might be:

public static void print2dIntArray(int[][] intArray){
   int rowIndex = 0;
   int colIndex = 0;
   while (rowIndex < intArray.length){
      while (colIndex < intArray[rowIndex].length){
         System.out.print(intArray[rowIndex][colIndex] + " ");
         colIndex = colIndex + 1;
       }
       System.out.println();
       rowIndex = rowIndex + 1;
       colIndex = 0;
   }
}//print2dIntArray

Notice how a lot more thinking is required when a loop with explicit control is used. It is a common problem to forget to deal with the indices, incrementing them properly and remembering to reset the column index to 0 for each row that is processed.

Yet Another Form of Repetition – for loop#

Java has another kind of loop: the original for loop (different from the for-each loop). This loop is just syntactic sugar for a while loop, which means that the for loop provides a different syntax that may help us remember the parts we need to consider where we make any loop:

  1. Initialization – starting a control variable at a certain value

  2. Boolean expression – to keep the loop going as long as the Boolean expression is true

  3. Change statement – to move the control variable in such a way as to (normally) progress towards making the Boolean expression false

The syntax of the for loop is:

for (<initialization>; <Boolean expression>; <change statement>){
\(\;\;\;\;\;\) <statements to repeat, i.e. loop body>
}

See if you can identify all the parts of the for loop in this example of printing the multiples of 5 from 0 to 25:

for(int mult = 5; mult <= 25; mult = mult + 5){
   System.out.print(mult + " ");
}
5 10 15 20 25 



Lick the Sugar: Fill in Each Part

While you can technically leave parts of the for loop blank, or even put multiple statements into each part, it is best to use each part for its intended purpose. Have one initialization, followed by one Boolean expression, followed by one change statement.



Let’s go back now to printing our 2d array of integers. With a for loop, we can make it look simpler than with a while loop:

public static void print2dIntArray(int[][] intArray){
   for (int rowIndex = 0; rowIndex < intArray.length; rowIndex++){
      for (int colIndex = 0; colIndex < intArray[rowIndex].length; colIndex++){
          System.out.print(intArray[rowIndex][colIndex] + " ");
      }
      System.out.println();
   }
}//print2dIntArray



Array of \(n\) Dimensions Need Loops of \(n\) Levels

For example, if you want to print a 1D array, you need a simple 1-level loop. To print a 2D array you will need a 2-level loop, i.e. nested. To print a 3D array you will need a 3-level loop, i.e. doubly nested, or triple loop.



Practice Questions#

  1. Write a Java Program to make a 3 X 4 X 5 array, and fill it entirely with asterisks.

  2. Use a for loop to sum the odd numbers from 1 to 29, inclusive. Then print the result.

  3. Write a Java method that takes a 2D array of integers and doubles the array’s values. Use only for in any loops you make, do not use while.

  4. Given the following code:

    1.  int[][] kiwi = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
    2.  for (int ruby = kiwi.length - 1; ruby > 0; ruby--){
    3.     for (int gold = 0; gold < kiwi[ruby].length; gold = gold + 2){
    4.        System.out.print(kiwi[ruby][gold] * ruby + " ");
    5.     }
    6.     System.out.println();
    7.  }
    

    a. Identify the change statements
    b. Identify the Boolean expressions
    c. Identify the initialization conditions

  5. Draw the execution trace for the code in question 4, and describe each step.

  6. Describe what the code in question 4 does using a natural language such as English.

  7. What is incorrect in this code to sum the integers from 10 to 100 inclusive:

    int sum = 0;
    for (int i; i < 100; i++){
       sum = sum + i;
    }
    System.out.println("sum: " + sum);
    
  8. What is incorrect in this method to change the entries in a 2d integer array to their absolute values?

    public static void int2dArrayToAbsVal(int[][] intsGrid){
       for (int row = 0; row < intsGrid.length; row++){
          for (int col = 0; col < intsGrid.length; col++){
             if (intsGrid[col][row] < 0){
                intsGrid[col][row] = -intsGrid[col][row];
             }
          }
       }
    }//int2dArrayToAbsVal
    

To Solutions