neon lights showing through ceiling window

6.2 Java | Processing 2D Arrays & Passing 2D Arrays to Methods

Processing Two Dimensional Array

Nest for loops are often used to process a two dimensional array.

Suppose an array matrix is made as follows:

The following are some examples of processing two dimensional arrays:

1. Initializing arrays values by User Input.

The following loop initializes the array with user input values:

2. Initializing arrays with random values.

The following loop initializes the array with random values between 0 and 99:

3. Printing arrays.

To print a two-dimensional array, you have to print each element in the array using a loop like the following:

4. Summing all elements.

Use a variable named total to store the sum. Initially total is 0. Add each element in the array to total using a loop like this:

5. Summing elements by column.

For each column, use a variable named total to store its sum. Add each element in the column to total using using a loop like this:

*Notice that column & row switched top & bottom order between examples 4. & 5. (this one)

6. Which row has the largest sum?

Us variables maxRow and indexOfMaxRow to track the largest sum and the index of the row. For each row, compute its sum and update maxRow and indexOfMaxRow if the new sum is greater.

7. Random shuffling.

Shuffling the elements in a one-dimensional array was introduced in ___ . How do you shuffle all the elements in a two dimensional array? To accomplish this, for each element matrix[i][j], randomly generate indices i1 and j1 and swap matrix[i][j] with matrix[i1][j1], as follows:

Passing Two Dimensional Arrays to Methods

When passing a two dimensional array to a method, the reference of the array is passed to the method.

You can pass a two dimensional array to a method just as you pass a one dimensional array. You can also return an array from a method. The example below shows 2 methods. The first method, getArray(), returns a two dimensional array, and the second method, sum(int[][] m), returns the sum of all the elements in a matrix.


Java PassTwoDimensionalArray results

Further Explanation

The methods getArray prompts the user to enter values for the array:

and returns the array:

The method sum:

has a two dimensional array argument. You can obtain the number of rows using m.length:

and the number of columns in a specified row using m[row].length:

◄◄◄BACK | NEXT►►►

What's Your Opinion?