60.8k views
3 votes
CSA U8 Review Sheet - 2D Arrays

1. Declare and create a String 2D array named list1 that has 3 rows and 2 columns. String[ ][ ] list1 = new String[3][2]
2. Initialize a 2D array of integers named nums so that it has 1,2,3 in the first row and 4, 5, 6 in the second row. int [ ][ ] nums = {{1,2,3},{4,5,6}}
3. Show how to determine the number of rows in the two-dimensional integer array, int z[][] z.length
4. Show how to determine the number of columns in the two-dimensional integer array, int z[][] z[0].length

User Juuga
by
5.4k points

1 Answer

3 votes

Answer:

  1. public class Main {
  2. public static void main (String [] args) {
  3. String [][] list1 = new String[3][2];
  4. int[][] nums = {{1,2,3}, {4, 5, 6}};
  5. int z[][] = {{1,2,3,4}, {5, 6, 7, 8, 9}};
  6. System.out.println(z.length);
  7. for(int i=0; i < z.length; i++){
  8. System.out.println(z[i].length);
  9. }
  10. }
  11. }

Step-by-step explanation:

Solution code is written in Java.

The best way to review the array topic is to create a Main program to write the relevant codes to create and manipulate array.

Firstly, create a two dimensional array using double square bracket syntax [] [] (Line 4). We put row and column number in each of the square bracket (new String [3] [2] ). The statement in Line 4 will create a two dimensional array with 3 rows and 2 columns.

We can also directly initialize a two dimensional array by enclosing the elements inside the curly brackets (Line 6).

To get the number of row, we can use length property. For example, z.length will give the number of rows in the two dimensional z array (Line 8-9).

To get the number of columns in each row, we can create a for loop to traverse through each row and use the i index to address each array row and use dot syntax to get the length property of each row which equivalent to number of columns (Line 11 - 13).

User FunctorSalad
by
5.6k points