170k views
5 votes
1) Create the following 2D array in one instruction: {{1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}} // your code goes below:

2) Create the above 2D array using a for loop and the below method: public static int[] simpleArray(int n) { int[] result = new int[n]; for (int i=0; i

1 Answer

1 vote

Answer:

1)

int[][] a2dArray = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};

2)

public class Main

{

public static void main(String[] args) {

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

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

a2dArray2[i] = simpleArray(5);

}

for (int i=0; i<a2dArray2.length; i++) {

for (int j=0; j<a2dArray2[i].length; j++){

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

}

System.out.println();

}

}

public static int[] simpleArray(int n){

int[] result = new int[n];

for (int i=0; i<n; i++) {

result[i] = i+1;

}

return result;

}

}

Step-by-step explanation:

1) To create a 2D array you need to write the type, two brackets and the name on the left hand side. Put the values on the right hand side.

2) Declare the array. Since there will be 3 rows and 5 columns, put these values in the brackets on the right hand side.

Create a for loop that iterates 3 times. Call the method simpleArray inside the loop so that each row of the a2dArray2 array will be set. Be aware that simpleArray method takes an integer as parameter and creates a 1D array, the numbers in the array starts from 1 and goes to the parameter value. That is why calling the method simpleArray (with parameter 5) 3 times will create a 2D array that has 3 rows and 5 columns.

Then, use a nested for loop to display the 2D array.

User Brettywhite
by
6.5k points