8.2.4. Enhanced For-Each Loop for 2D Arrays (Day 2)

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array. We loop through each of the inner arrays and loop through all the values in each inner array. Notice the type of the outer loop array variable – it is an array that will hold each row!

Nested enhanced for loops demo.

In this case the for (int[] colArray : a) means to loop through each element of the outer array which will set colArray to the current column array. Then you can loop through the value in the column array.

You can step through this code using the Java Visualizer by clicking on the following link3

8.2.5. 2D Array Algorithms

All of the array algorithms can be applied to 2D arrays too. For example, counting and searching algorithms work very similarly. The following code adds all of the values in a given row.

coding exercise Coding Exercise

What will the following code print out? Can you add another method that gets the total for a column?

You can loop through just part of a 2D array. You can change the starting value and ending value to loop through a subset of a 2D array.

Loooping through just part of a 2D array.

Here is a linear search algorithm where we access each row and then apply a linear search on it to find an element.

coding exercise Coding Exercise

What will the following code print? Can you change the code to work for a String 2D array?

8.2.6. groupwork Programming Challenge : Picture Lab

Photographs and images are made up of a 2D array of pixels which are tiny picture elements that color in the image. 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 to experiment. Can you make black? Can you make white? Can you make purple?

Scroll down to the bottom of the following code and take a look at the switchColors method. Run the code and watch what it does. It switches RGB values of each pixel and the colors change!

Picture Lab

Now, write a similar method called zeroBlue() that sets the blue values at all pixels to zero. You can test it in the active code above or on this Repl.it Swing project or this alternative Repl.it project by teacher Jason Stark from LA (click output.jpg to see the result) or your own IDE to see what it does.

Here are some more exercises from the Picture Lab:

You can continue on with the Picture Lab to mirror images and create collages and detect edges as the first step in recognizing objects in images.

8.2.7. Summary

You have attempted of activities on this page