In this post, I am going to explain how to loop over a two dimensional array.
What is a multi-dimensional array?
Multidimensional arrays are the arrays of arrays.
Syntax to create two dimensional Array
dataType arrayName[][] = new dataType[size1][size2]
(OR)
dataType[][] arrayName;
arrayName = new dataType[size1][size2]
Example
int arr[][] = new int[3][4];
Above snippet creates a 3 * 4 array, where array has 3 rows and 4 columns.
As shown in the above image,
a. 0th row and 3rd column has value 4 and it can be accessed with index notation like arr[0][3].
b. 2nd row and 1st column has value 10 and it can be access with index notation like arr[2][1].
Let’s see below examples to print two dimensional array content using for, while and do-while loops.
Using two for loops
for(int row = 0; row < noOfRows; row++) {
for(int column = 0; column < arr[row].length; column++) {
System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
}
System.out.println();
}
ArrayTraversalUsingForLoop.java
package com.sample.app;
public class ArrayTraversalUsingForLoop {
public static void main(String[] args) {
final int arr[][] = {
{2, 3, 5, 7},
{11, 13, 17},
{19, 23, 29, 31, 37, 41}
};
final int noOfRows = arr.length;
for(int row = 0; row < noOfRows; row++) {
for(int column = 0; column < arr[row].length; column++) {
System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
}
System.out.println();
}
}
}
Output
arr[0][0] = 2 arr[0][1] = 3 arr[0][2] = 5 arr[0][3] = 7 arr[1][0] = 11 arr[1][1] = 13 arr[1][2] = 17 arr[2][0] = 19 arr[2][1] = 23 arr[2][2] = 29 arr[2][3] = 31 arr[2][4] = 37 arr[2][5] = 41
Using while loops
final int noOfRows = arr.length;
int row = 0;
while(row < noOfRows) {
int column = 0;
while(column < arr[row].length) {
System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
column++;
}
row++;
System.out.println();
}
ArrayTraversalUsingWhileLoop.java
package com.sample.app;
public class ArrayTraversalUsingWhileLoop {
public static void main(String[] args) {
final int arr[][] = {
{2, 3, 5, 7},
{11, 13, 17},
{19, 23, 29, 31, 37, 41}
};
final int noOfRows = arr.length;
int row = 0;
while(row < noOfRows) {
int column = 0;
while(column < arr[row].length) {
System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
column++;
}
row++;
System.out.println();
}
}
}
Array traversal using do-while loop
ArrayTraversalUsingDoWhileLoop.java
package com.sample.app;
public class ArrayTraversalUsingDoWhileLoop {
public static void main(String[] args) {
final int arr[][] = {
{2, 3, 5, 7},
{11, 13, 17},
{19, 23, 29, 31, 37, 41}
};
final int noOfRows = arr.length;
int row = 0;
do {
int column = 0;
do {
System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
column++;
}while(column < arr[row].length);
row++;
System.out.println();
}while(row < noOfRows);
}
}
No comments:
Post a Comment