Convert Two Dimensional Array into One Dimensional Array in Java

In this program, you'll learn to Convert two dimensional array into one dimensional array in Java.

Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects.

For example, an array of ints will have the type int [ ]. Similarly we can have int [ ][ ], which represents an "array of arrays of ints". Such an array is said to be a two-dimensional array.

A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself. For example,

   int [ ][ ] A = new int [3][5]; 


Declares a variable, A, of type int [ ][ ], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.

To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop.

 int [ ][ ] A = new int [5][4]; 
  // print array in rectangular form 
  for (int i=0; i<A.length; i++) { 
      for (int j=0; j<A[i].length; j++) { 
          System.out.print(" " + A[i][j]); 
      } 
      System.out.println(""); 
  }


In this example, "int[ ][ ] A= new int [5][4];" notation shows a two-dimensional array. It declares a variable A of type int [ ][ ],and it initializes that variable to refer to a newly created object. The notation int [5][4] indicates that there are 10 arrays of ints in the array A, and that there are 5 ints in each of those arrays.

Convert Two Dimensional Array into One Dimensional Array


When you run the program, the output will be:

Enter the value of row : 5
Enter the value of column : 4
Element are Stored in Matrix in row 5 Coloum 4
53     15     89     56     
90     30     23     53     
78     24     46     27     
11     59     78     55     
35     46     68     23     
Element converted to array & Array length is 20
53 15 89 56 90 30 23 53 78 24 46 27 11 59 78 55 35 46 68 23 

أحدث أقدم