Activity 4.48.1.
Replace the βADD CODE HEREβ below with the code to declare and create a 3 by 3 two-dimensional int array named
table
. The finished code will print the values 0 to 8.
Solution.
Declaring and creating a 3 by 3 two-dimensional int array only takes one line. To declare the array specify the type of values in the array followed by [][] to indicate a 2D array and then provide a name for the array. To create the array add an
= new
, followed by the same type as before and [num rows][num cols]
.
public class Test1
{
public static void main(String[] args)
{
int[][] table = new int[3][3];
int count = 0;
for (int row = 0; row < table.length; row++)
{
for (int col = 0; col < table[0].length; col++)
{
table[row][col] = count;
count++;
System.out.print(table[row][col] + " ");
}
}
}
}