Consider the following definitions
int[ ][ ] numbers = {{1, 2, 3},
{4, 5, 6} };
The following code below produces
for (int row = numbers.length - 1; row >= 0; row -- )
{
for (int col = 0; col < numbers[0].length; col ++)
{
System.out.print (numbers [row][col]);
}
}
The code produces the following output:
456123
Explanation:
//Here is a 2D array with 2 rows and 3 columns
int[ ][ ] numbers = {{1, 2, 3}, {4, 5, 6} };
//the for loop below starts from values row= 2-1 = 1
// so the loop runs from 1 to 0
for (int row = numbers.length - 1; row >= 0; row -- )
{
// this loop is for each columns runs from 0 to less than 3
// here we are accessing 0th, 1st and 2nd columns of each row
for (int col = 0; col < numbers[0].length; col ++)
{
// printing the current index value of 2d matrix numbers
System.out.print(numbers [row][col]);
}
}
so , if you see we counting rows 1 to 0
and columns from 0 to 2
1st row 0th,1st and 2nd column values gets printed followed by 0th row 1st and 2nd column values gets printed.
456123
Get Answers For Free
Most questions answered within 1 hours.