Sunday, August 8, 2021

How to loop over two dimensional array in Java? Example

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other. Though it's not common to see an array of more than 3 dimensions and 2D arrays is what you will see in most of the places. It's one of the most useful data structures in the programming world. You can use a two-dimensional array to make finite state machine (FSM) solve state-based problems, you can use a 2D array to create board games like Chess, Sudoku, and Tic-Tac-To and you can even use a two-dimensional array to create 2D arcade games e.g. Tetris, Super Mario Bros and so on. Whatever you see on your screen is nothing but a 2D array that is populated using tiles.

In order to make use of the 2D array, you must know how to populate and iterate over it and that's what you will learn in this article. You can think about a two-dimensional array as a matrix that has rows and columns, this helps to visualize the contents of an array. In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other.

Anytime, if you want to come out of the nested loop, you can use the break statement. If you are an absolute beginner and just started with programming, I recommend reading Head First Programming first. Once you went through the book, most of the programming concepts e.g. array, string, a vector will make sense to you.


Java Program to Loop over 2D Array in Java

Here is a Java program to iterate over a two-dimensional array in Java using traditional for loop. Though it's not necessary to use for loop, you can even use while loop or advanced for loop in Java, it makes sense to start with this simplest of programming construct.



In this example, we have first created a 2-dimensional array of size 4x4, which means 4 rows and 4 columns. Then we have looped over it two times, first time to populate the array with integer values and the second time to go through each index and print their values.

It's not necessary to start looping from the first element e.g. [0, 0] which is the first row and first column but if you want to touch every element this is the right place to start.

Here is the code to loop over a 2D array in Java :

 for (int row = 0; row < board.length; row++) {
    for (int col = 0; col < board[row].length; col++) {
       board[row][col] = row * col;
    }
 }

You can see that the outer loop is going through each row and the inner loop is going through each column, this way we go over all elements. In the first iteration, all elements of the first row are processed, just like iterating over one-dimensional array.

Here is the complete program :

How to loop over two dimensional array in Java


Looping over a 2D array in Java - Example


/**
 * Java Program to demonstrate how to loop over two-dimensional array.
 * We first loop to populate the array and later to print values. 
 * 
 * @author WINDOWS 8
 */
public class TwoDimensionalArrayDemo{

    public static void main(String args[]) {

        // let's create board of 4x4
        int[][] board = new int[4][4];

        // let's loop through array to populate board
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                board[row][col] = row * col;
            }
        }

        // let's loop through array to print each row and column
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                board[row][col] = row * col;
                System.out.print(board[row][col] + "\t");
            }
            System.out.println();
        }
    }

}

Output :
0   0   0   0   
0   1   2   3   
0   2   4   6   
0   3   6   9   


BTW, Java doesn't really have multi-dimensional arrays, instead, you have arrays of arrays (of arrays ...). So, if you want to loop through the first array, you ask for "board[0].length", if you want to loop through the second array, you ask for "board[1].length".

As I told you, a multi-dimensional array is one of the popular data structures and can be used to represent board games like Chess, Ludo, Sudoku, Tetris, and also equally useful to draw terrains in tile based games. In fact, it is one of the most useful data structures in game programming. Another natural use of a multi-dimensional array is in matrix maths e.g. matrix multiplication, adding two matrices, transposing matrices, etc.

You can extend this technique to loop through the multi-dimensional array in Java. You will just need as many loops as many dimensions your array has. Remember, you can declare a two-dimensional array in Java without specifying the length of the second dimension.


Other Java Articles you may like
  • What Every Java Developer Should know about Array (see here)
  • 22 Array concept Interview Questions in Java (see here)
  • How to print array values in Java? (example)
  • How to compare two arrays in Java? (example)

4 comments:

  1. What is the best way to iterate over two dimensional array? is for loop is the only way? can't we use while loop or do while loop? how about Iterator? I heard array implements Iterable interface in Java? And finally, does Java 8 change the way you loop over multi-dimensional array in Java?

    ReplyDelete
  2. how to solve this question please Index 0 represents grades in the range of 90 - 100
    Index 1 represents grades in the range of 80 - 89
    Index 2 represents grades in the range of 70 - 79
    Index 3 represents grades in the range of 60 - 69
    Index 4 represents grades in the range of 59 or below

    Display the number of A's, B's, C's, D's, and F's; also display the average, highest, and lowest grade.
    Here is what your program should look like:

    Enter a numeric grade (0-100) or -1 to quit: 90

    Enter a numeric grade (0-100) or -1 to quit: 82

    Enter a numeric grade (0-100) or -1 to quit: 96

    Enter a numeric grade (0-100) or -1 to quit: -1

    Number of A grades: 2

    Number of B grades: 1

    Number of C grades: 0

    Number of D grades: 0

    Number of F grades: 0

    Average is: 89.33

    Highest grade is: 96

    Lowest grade is: 82

    ReplyDelete
  3. how to print 4x4 dollar grid in java
    such as
    $ $ $ $
    $ $
    $ $
    $ $ $ $
    please show me

    ReplyDelete
  4. 8 7 6 5 4 3 2 1 0 this in two dimensional array 3by3

    ReplyDelete