Showing posts with label Arrays in Java. Show all posts
Showing posts with label Arrays in Java. Show all posts

Aug 23, 2020

2-D Array in Java | JAVA Language | Coding Winds

2D ARRAYS

Hey guys, we are back with another blog in java and today we are gonna talk about 2D arrays in java. So we are acknowledged with arrays in java but today we will see that how can we create a 2D one. So what are 2D arrays in java? Basically, arrays which consists of rows and columns are known as 2D arrays. With the help of 2D arrays we can create a matrix in our code, lest solve matrix related problems. Now let us see how can we declare a 3D array and store values inside it.

Initializing of a 2D array:

For declaration of a 2D array we can follow the general syntax given below

 

type arrayName[][] = new type [size of row in INT][size of column in INT];

 

int ar[][]= new int[3][2];

 

So basically in the above declaration we have declared a 2D array or a matrix which has 3 rows and 2 columns. Firstly let's see how can we initialize the  2D array directly in our code:

 

import java.util.Scanner;

public class Two_D_Arrays {

     public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

         int ar[][]= {

                        { 1, 2 },

                        { 3, 4 },

                        { 5, 6 },

                      };

         //printing the 2d array

         for(int i=0; i<3; i++)

         {

              for(int j=0;j<2; j++) {

                  System.out.print(ar[i][j]+" ");

              }

              System.out.println("");

         }

     }

}

OUTPUT:

1 2

3 4

5 6

 

Now we will see how can we use two loops to get elements as inputs for our 3X2 matrix, below is  the code for taking the input and then printing  out the whole matrix.

import java.util.Scanner;

 

public class Two_D_Arrays {

     public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

         int ar[][]= new int[3][2];

         int temp=0;

    

         //Taking user input for the array

     /*the loop will will take the inputs for the following indexes

          ar[0][0]        ar[0][1]      

          ar[1][0]        ar[1][1]

          ar[2][0]        ar[2][1]

          */

         for(int i=0; i<3; i++)

         {

              for(int j=0;j<2; j++) {

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

              }

         }

         //printing the 2d array

         for(int i=0; i<3; i++)

         {

              for(int j=0;j<2; j++) {

                  System.out.print(ar[i][j]+" ");

              }

              System.out.println("");

         }

     }

}

OUTPUT:

1 2

3 4

5 6

Note that the output is printed in a way that it actually represents a matrix of order 3X2 i.e., 3 rows and 2 columns.

That's it for today guys, in our upcoming blogs we will learn about the memory allocations regarding arrays. Till then keep reading, keep coding!