1 Attachment(s)

Can someone explain the logic behind looping through multidimensional arrays?

Let say i have this code:

Code :

public class ArrayDemo {
public static void main (String[]args) {
int [][] numbers = {{5,3,2},{7,5,3}};
int sum=0;
int index1;
int index2;
for (index1 =0; index1< numbers.length; index1++) {
for (index2 =0; index2< numbers[index1].length; index2++) {
sum += numbers[index1][index2];
}
}
System.out.println("Sum: " + sum);
System.out.println("Length: " + numbers.length);
}}

this is output

Attachment 2285

What does the statement

Code :

for (index2 =0; index2< numbers[index1].length; index2++)

mean?

And why does the length = 2?

Please i need an explanation in layman's terms.Thanks

Re: Can someone explain the logic behind looping through multidimensional arrays?

Please break down each element of the for loop you've highlighted and tell us what you think it means. For example, write your explanation for each of the following:

index1:

index2:

numbers:

numbers[index1]:

numbers[index1].length:

index2++:

Re: Can someone explain the logic behind looping through multidimensional arrays?

ehm,

index1 = the index of the first element (row) in the array, say numbers[0][1], no?

index 2 = the index of the first element (column) in the array

numbers = the array

numbers[i]= the current index the loop is in

numbers[i].length (no idea, this is in fact the source of my confusion)

index2++ = no idea.

Re: Can someone explain the logic behind looping through multidimensional arrays?

Good job, and that little exercise pointed to the source of your confusion.

Some disagree with the description of arrays in Java as "multi-dimensional." They insist, for example, that a 2D array in Java, myArray[x][y], is 'x' arrays of 'y' arrays, and 'y' doesn't have to be the same for each 'x'. That's why the notation you're confused about is important.

Imagine the array was defined this way instead of the way in your original post:

int [][] numbers = {{5,3,2},{7,5}};

In this case, y = 3 elements in the first row but only 2 elements in the second row. Then to get the iteration right in nested for loops, the inside loop - the one that iterates through each column element - has to account for this difference in length:

Code java:

numbers.length = 2 // for 2 rows
numbers[0].length = 3 // for 3 elements in the first row (3 columns)
numbers[1].length = 2 // for 2 elements in the second row (2 columns)

Hope this helps.

Re: Can someone explain the logic behind looping through multidimensional arrays?

Thanks.That explains a lot

Re: Can someone explain the logic behind looping through multidimensional arrays?

thanx to all nice sharing . this thread help me lot of..