This is homework that we got in my Computer Science class dealing with 2D Arrays. I tried understanding the code, but unfortunately, I'm having a hard time understanding some of the code. This is the code that we were provided with:
public class Magic {
public static void main(String[] args) {
// Initializing a variable named n and assigning the integer 3 to it
int n = 3;
// Initializing a multi-dimensional array with 3 rows and 3 columns max
int m[][] = new int[n][n]; // 3 by 3
int i, j;
// Assigning 1 to variable num
int num = 1;
int nn = n * 3 / 2; //4
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++;
System.out.println(num);
} // next j
} //next i
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(m[i][j] + "\t");
} // next j
System.out.println();
} //next i
} //end main()
} //end class Magic
Now my problem is that I don't understand this snippet of code specifically:
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++;
}
}
What does this line of code do in the loop? I'm not sure why the modulus is also used in this line. Is it there to limit the range of the generated numbers?
m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++;