Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to pass the input through 2d array argument in java

+9 votes
asked Jul 17, 2024 by Bhakthi HS (210 points)

2 Answers

+1 vote
answered Jul 18, 2024 by Divya Prakash Ray (160 points)

you can use two 'for loops' to take the input in a 2d array. Basically we can visualize a 2d array as an simple array in which all the individual elements are themselves an array. So the first 'for' loop will is used for traversing the main array index while the 2nd 'for' loop is used to input the elements in the inner array at a particular index.

01234567
a1b1c1d1e1f1g1h1
a2b2c2d2e2f2g2h2
a3b3c3d3e3f3g3h3
a4b4c4d4e4f4g4h4

 for(int i=0 ; i<n1 ; i++){                           // n1 is the no. of arrays in the main array\

for(int j=0 ; j<n2;j++){                             // n2 is the no. of elements in the subsequent arrays

arr[i][j] = sc.nextInt();

}}

+1 vote
answered Jul 19, 2024 by Peter Minarik (101,360 points)

I've put together a small code where one can pass 2d arrays as arguments to functions. This demonstrates that we pass arguments by reference as loadIdentity changes the array:

public class Main
{
    public static void loadIdentity(int[][] array)
    {
        for (int row = 0; row < array.length; row++)
        {
            for (int column = 0; column < array[row].length; column++)
            {
                array[row][column] = row == column ? 1 : 0;
            }
        }
    }
    
    public static void print(int[][] array)
    {
        for (int row = 0; row < array.length; row++)
        {
            for (int column = 0; column < array[row].length; column++)
            {
                System.out.print(array[row][column] + " ");
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args)
    {
        int[][] array = {{1, 2}, {3, 4}};

        System.out.println("Original array:");
        print(array);

        System.out.println();
        System.out.println("Identity array:");
        loadIdentity(array);
        print(array);
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...