In this exercise, you will write a program NbyN containing a static method nbyn() with the following signature:
public static int[][] nbyn(int N)
The goal is to create an N-by-N matrix (where the value of N is supplied by the int parameter N) which meets the conditions:
- The diagonal contains the value of the current row/column.
- All other cells should contain 0.
Here is a picture of what the matrix should look like occur when N = 4.
0 | 0 | 0 | 0 |
0 | 1 | 0 | 0 |
0 | 0 | 2 | 0 |
0 | 0 | 0 | 3 |
Write the function nbyn() so that it returns a 2D array that meets the specification above.
Note
You will need two nested for loops: the outer one will be responsible for the rows, and the inner one will be responsible for the columns (i.e., the cells in each row).
In addition, define a main() method which will call nbyn(10) and print out the result.
As you have probably noticed, if a is an array, then calling System.out.println(a) just produces an unhelpful output such as [[I@35960f05. Given the techniques you have been taught so far, your only option is to use a for loop to iterate over each element of the array and print out the elements one by one. In order to print out a 2D array, you will need two nested for loops, just as you did for assigning values to the array in the first place. Try to do this so that the output looks just like the following:
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 9
An automated test has been created for this exercise: NbyNTest.java.