How to use 2D array? - ICSE Java Expert

Breaking

ICSE Java Expert

Learn Java for school

Unordered List

WELCOME

Thursday, August 09, 2018

How to use 2D array?



2D ARRAY

How to declare an integer array of size 5?

        int ar1[]=new int[5];                        // declaration of 1D array

How to declare an integer array of size 5 and initialize the same?

        int ar2[]={5,6,7,8,8};                      // declaration & initialization of 1D array

How to print the elements of an integer array?

        int ar2[]={5,6,7,8,8};                      // declaration & initialization of 1D array
        for(int i=0;i<ar1.length;i++)             // loop for accessing all elements of the array
        {
            System.out.println(ar1[i]+" ");     // printing the elements of the array
        }

How to initialize a 2D array at the time of declaration?

        int ar3[][]={                                  // declaration and initialization of 2D array
                {5,6,7,9,8},
                {5,8,8},
                {4,3,2,8}
            };

How to access the elements of a 2D array?

        for(int i=0;i<ar3.length;i++)             // outer loop is for accessing rows
        {
            for(int j=0;j<ar3[i].length;j++)      // inner loop is for accessing columns
            {
                System.out.print(ar3[i][j]+" ");  // printing the elements in tabular form
            }
            System.out.print("\n");                 // changing the line after one row
        }

No comments:

Post a Comment