How to use for loop with two dimensional array in Java

Published by user on

In this post, we will look at how to use for loop with two dimensional array in Java. When we embed one for loop in another then it is known as nested for loop.

To loop over two dimensional array in Java you can use two for loops. Each loop uses an index. Index of outer for loop refers to the rows, and inner loop refers to the columns. You can then get each element from the array using the combination of row and column indexes.

Generally speaking, I have rarely seen more than 4-dimensional array, in most cases, two dimensional array solves the problem. Most of the problems that include board, matrix or grid can be solved using two dimensional array.  So it becomes very important to understand how to assign values to two dimensional array and loop over it.

Java doesn’t support multidimensional array by default. When we implement a 2d array, it is actually the arrays of an array.

Program to demonstrate for loop with two dimensional array


public class ForLoopExample {
	public static void main(String[] args) {
		int[][] values = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		
		System.out.println("Elements are :");
		for(int i=0; i< values.length; i++) {
			for(int j=0; j< values[i].length; j++) {
				System.out.print(values[i][j] + "\t");
			}
			System.out.println("");
		}
	}
}

Output:

Elements are :
1	2	3
4	5	6
7	8	9

Explanation:
The above program iterated each row and then for each row, we looped through each column.

Let’s try to visualize the iteration.

iterate-two-dimensional-array-for-loop

 

Variable ‘i’ specifies rows and ‘j’ specifies columns, both of them together identifies an element. As ‘i’ progress we get hold of the next row. We loop through till the length of two dimensional array.

In case if you want to come out of a nested loop, you can use the break statement. The break statement terminates the loop and starts executing the next statement.

Loop two dimensional array using enhanced for loop

/**
 * Program to demonstrate iterating two dimensional array using enhanced for
 * loop
 */
public class TwoDimensionalArrayEnhancedForLoop {
	public static void main(String[] args) {
		int[][] contents = { { 88, 66, 79 }, { 56, 25, 39 }, { 58, 47, 69 } };

		System.out.println("Loop Using Enhanced for loop:");
		for (int[] eachRow : contents) {
			for (int j : eachRow) {
				System.out.print(j + "\t");
			}
			System.out.println("");
		}
	}
}

Output:

Loop Using Enhanced for loop:
88	66	79	
56	25	39	
58	47	69	

Explanation:
In the traditional method, we dealt with the index and fetched elements. But in enhanced for loop we get hold of the row, and for each row we get the values of elements.
When we say row, we get hold of int[] and then we can iterate this int[] and print or process each element.
Use enhanced for loop when you don’t want to know the index of the element you are currently processing. As we saw code becomes clear and concise when we use enhanced for loop.

Most of the time the multidimensional arrays are restricted to 2d and 3d. If you want to loop over ‘n’ dimensional array then you can have that many nested loop and process the elements.

You have learned a very useful concept of iterating a two dimensional array in Java. If you liked this article please share it.

Categories: Java