0

I was told that there was a convention when you have a code to print an array, that there is a value that must come first than the other one, for example:

for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; column++)
            System.out.print("" + array[i][j]);}

Would be i first or it needs to be j first? I find answers like this one but they don't solve my doubt...

PS: I'm not asking just about Java, but about C#, C, C++, Javascript, etc.

Community
  • 1
  • 1
yamilelias
  • 305
  • 2
  • 16

2 Answers2

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

means that i serves as an index for the elements of array (the elements happen to be sub arrays).

for (int j = 0; j < array[i].length; column++)

indicates that j serves as an index for the elements of array[i] (the sub arrays of array).

So yes, i needs to be before j.

jh314
  • 27,144
  • 16
  • 62
  • 82
0

The convention is to do it in order, as you have written:

for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; column++)
            System.out.print("" + array[i][j]);}

Here, i is before j in the loops, and array is indexed by i before j as well.

This is the natural order, as written in the code. It is also the order in which the memory elements are stored in most languages (Java, C#, C, C++). This is called row-major order, where elements in the same row are in contiguous memory locations.

For a 3 by 3 array a[3][3] in row-major order, the elements are stored as:

a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2]

Indexing into the array in row-major order also has performance benefits. By accessing memory sequentially, you minimise cache misses.

ronalchn
  • 12,225
  • 10
  • 51
  • 61