Skip to main content
Logo image

Section 4.12 2D Array Traversals: Nested Loops

90 minutes
In this lesson, you will learn how to use nested loops to traverse 2D Arrays.

Subsection 4.12.1 Nested Loops

Nested iteration statements (loops) are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects.
Here is an example of a nested for loop (one loop inside of another loop) to loop/traverse through all of the elements of a 2D array.
int[][] array = { {1,2,3},{4,5,6}};
for (int row = 0; row < array.length; row++)
{
    for (int col = 0; col < array[0].length; col++)
    {
         System.out.println( array[row][col] );
    }
 }

Activity 4.12.1.

What does the following code do? Add another row of numbers to the matrix. Will the loops traverse this row too? Use the CodeLens button to trace through the code. Note that an array can be passed in as an argument to a method.
Some key things to notice about this code are:
  • total is declared to be a double so that the result will be a double. If total was declared to be an int then the result would be an integer and the values after the decimal point would be thrown away.
  • The array is passed in as an argument to the method.
  • The number of rows is a.length
  • The number of columns is a[0].length
  • The number of times this loop executes is the number of rows times the number of columns.

Subsection 4.12.2 Row-Major and Column-Major Traversals

Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row (and is more common), whereas column-major order traversal occurs down each column. Here’s an example of nested loops that traverse the 2D array in column-major order.

Activity 4.12.2.

What will the following code print out? Try to guess before you run it.

Activity 4.12.3.

Consider the following code segment. What is the last row of numbers printed when this code segment is executed?
 int[][] points = { {11, 12, 13, 14, 15},
                    {21, 22, 23, 24, 25},
                    {31, 32, 33, 34, 35},
                    {41, 42, 43, 44, 45}};
 for (int row = 0; row < points.length; row++)
 {
     for (int col = points[0].length - 1; col >= row; col--)
     {
          System.out.print(points[row][col] + " ");
     }
     System.out.println();
}
  • 45 44 43 42 41
  • Trace through the code. Notice that the inner loop stops at index row.
  • Trace through the code. Notice that the inner loop stops at index row.
  • 41 42
  • Trace through the code. Notice that the inner loop works through the row backwards.
  • 45 44
  • Correct!
  • 44 45
  • Trace through the code. Notice that the inner loop works through the row backwards.

Subsection 4.12.3 Enhanced For-Each Loop for 2D Arrays

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for (for each) loop to loop through all elements in an array. Enhanced for loops are much simpler to use since you don’t have to use the indices and the []’s, but you can only use them if you are not going to change the values in an array of primitive types since the variable val below will not change the original array.
String[][] array;
// Nested For-each loops that traverse a 2D String array
for (String[] innerArray : array)
{
   for (String val : innerArray)
   {
       System.out.println(val);
   }
}
Memorize this pattern. The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array (String[] innerArray in the outer loop in the example above). The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array (String val in the inner loop in the example above). The type of the variables in the for-each loops must match the type of the array.
It is important to remember the limitations of enhanced for loops. They cannot change the array. Assigning a new value to the enhanced for loop variable (val above) does not change the value stored in the array.

Activity 4.12.4.

Nested for-each loops demo. Click on the CodeLens button to trace through the code.

Subsection 4.12.4 2D Array of Objects

Photographs and images are made up of a 2D array of pixels which are tiny picture elements that color in the image. For example, a pixel is shown at row 173 and column 214 of the image below.
The color of a pixel is represented using the RGB (Red, Green, Blue) color model, which stores values for red, green, and blue, each ranging from 0 to 255. You can make any color by mixing these values! Try the RGB Color Mixer
 1 
https://www.rapidtables.com/web/color/RGB_Color.html
to experiment. Can you make black? Can you make white? Can you make purple? You can learn more about pixels in the Picture Lab sections A1 to A3
 2 
pictureLabA1toA3.html
.
In Java, we can write a Pixel class to represent a pixel in an image at a given x and y coordinate.
public class Pixel
{
    private int x;
    private int y;
    /** Implementation not shown * */
}
The College Board Picture Lab
 3 
https://secure-media.collegeboard.org/digitalServices/pdf/ap/picture-lab-studentguide.pdf
contains a Pixel class and a Picture class that loads an image and creates a 2D array of pixels to represent it. For example, the Picture constructor below loads the image beach.jpg, and the getPixels2D method returns its 2D array of pixels. You can get and set the red, green, and/or blue value for a Pixel object to change its color.
Picture pict = new Picture("beach.jpg");
// A 2D array of pixels
Pixel[][] pixels = pict.getPixels2D();
Pixel p = pixels[0][0]; // get the first pixel
int blue = p.getBlue(); // get its blue value
System.out.println("Pixel (0,0) has a blue value of " + blue );
p.setBlue(255);  // set its blue value to 255
You can loop through all the Pixel objects in the two-dimensional array to modify the picture. The following code is the zeroBlue method in the Picture class. It uses nested loops to visit each pixel in a photo which has a color with red, green, and blue values, and it sets all the blue values to 0. You can experiment with this method and write your own methods to modify the pixels in the challenge below and the extended Picture Lab A5 Image Modification Exercises
 4 
pictureLabA5.html#image-modification-exercises
.
public void zeroBlue()
{
    Pixel[][] pixels = this.getPixels2D();
    for (Pixel[] rowArray : pixels)
    {
        for (Pixel p : rowArray)
        {
            p.setBlue(0);
        }
    }
 }

Subsection 4.12.5 Coding Challenge : Picture Lab

Figure 4.12.1.
In this challenge, you will do a part of the Picture Lab to modify the pixels of a digital photo. Scroll down to the bottom of the following code and take a look at the zeroBlue method. Run the code and watch what it does. It uses nested loops to visit each pixel in a photo which has a color with red, green, and blue values, and it sets all the blue values to 0.
Now, write a similar method called keepOnlyBlue that visits every pixel and sets the red and green values to zero but does not change the blue ones. Then, write a method called switchColors that swaps the red pixels with green pixels or blue pixels to change the colors around. You will need to use the getRed, getGreen, getBlue to get the RGB values of the pixel and then swap them around by using the setRed, setGreen, setBlue methods and giving them different color values from the get methods as arguments.
You can test the methods in the active code below or in this Replit Swing project
 5 
https://replit.com/@BerylHoffman/Picture-Lab
or this alternative Replit project
 6 
https://replit.com/@BerylHoffman/PictureLab-with-output-file
by teacher Jason Stark from LA (click output.jpg to see the result) or your own IDE to see what it does.

Project 4.12.5.

Picture Lab: 1) write a method called keepOnlyBlue() that keeps only the blue values by setting the red and green values to zero. Uncomment the code in main to test it. 2) write a method called switchColors() that replaces red values (using p.setRed) with green or blue values (using p.getGreen(), etc.) to change the colors around. Uncomment the code in main to test it.
Here are some more exercises from the Picture Lab A5 Image Modification Exercises
 7 
pictureLabA5.html#image-modification-exercises
:
  • Write a negate method to negate all the pixels in a picture. To negate a picture, set the red value to 255 minus the current red value, the green value to 255 minus the current green value and the blue value to 255 minus the current blue value.
  • Write the gray scale method to turn the picture into shades of gray. Set the red, green, and blue values to the average of the current red, green, and blue values (add all three values and divide by 3).
You can continue on with the next pages of Picture Lab A5 Image Modification Exercises
 8 
pictureLabA5.html#image-modification-exercises
to mirror images and create collages and detect edges as the first step in recognizing objects in images.

Subsection 4.12.6 Summary

  • (AP 4.12.A.1) Nested iteration statements (loops) are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects.
  • (AP 4.12.A.1) Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, whereas column-major order traversal occurs down each column.
  • (AP 4.12.A.2) The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
  • The 2D array’s length gives the number of rows. A row’s length array[0].length gives the number of columns.

Subsection 4.12.7 AP Practice

Activity 4.12.6.

Consider the following code segment. What is the value of sum as a result of executing the code segment?
int[][] arr = { {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12} };
int sum = 0;
for (int[] x : arr)
{
    for (int y = 0; y < x.length - 1; y++)
    {
         sum += x[y];
    }
}
  • Trace through the code.
  • Correct!
  • Trace through the code.
  • Trace through the code.
  • Notice that the inner loop goes up to but not including x.length - 1.

Subsection 4.12.8 2D Arrays and Loops Game

Try the game below to practice loops with 2D arrays. Click on Arrays and then check 2D and check Loops and then click on the elements of the * array that would be printed out by the given code. If you’re stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get.
You have attempted of activities on this page.