java – Show matrix rows

Question:

I have to build an array and display its last two rows with all its elements. I understand that the most traditional way to do it is something like this (I clarify that the variable "rows" was previously loaded by keyboard when asking how many rows and columns the matrix would have):

public void mostrarDosUltimasF() {

        System.out.println("fila ante ultima.................");
        for (int x = 0; x < mat[filas -1].length; x++) {
            System.out.println(mat[filas - 2][x]);
        }
        System.out.println("Fila ultima............");
        for (int x = 0; x < mat[filas-1].length; x++) {
            System.out.println(mat[filas - 1][x]);
        }

the question that I have and that I do not understand, is why I should put the -1 in both for. In the tutorial it says that since the space [0] [0] always exists, without that -1 the error "out of bounds" would be given. It's what happened to me when I tried to do it on my own. But I still do not understand the reason well since if the value of "rows" were for example 3, when starting the x of the for at 0, three reproductions would suffice. While my logic told me that putting the -1, the for would only be reproduced twice since the value would remain at 2. Everything works fine now but there is something that I am misunderstanding. Thanks a lot.

Answer:

Imagine you have this matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

If we put positions, it would be as follows:

[00, 01, 02]
[10, 11, 12]
[20, 21, 22]

where filas equals 3 , your for has the following

for (int x = 0; x < mat[filas - 1].length; x++)

which would be equal to:

for (int x = 0; x < mat[3 - 1].length; x++)

Now if we go back to the matrix we have that mat[3 - 1] or mat[2] is the last row:

[00, 01, 02]
[10, 11, 12]
[20, 21, 22]  <=  Exactamente aqui esta la fila 2

Which in your matrix with data would be:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]  <=  Esta es la fila 2

and if we continue replacing you would have the following:

for (int x = 0; x < [7, 8, 9].length; x++)

What in the end would be:

for (int x = 0; x < 3; x++)

What would help you to go through the three values ​​that you have in that row, now if you had:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 1, 2, 3]

When performing the length - 1 of the for you would have:

for (int x = 0; x < 4; x++)

and thus it is ensured that whatever the dimension of the row is, that code will always run.

I hope my explanation is understood;) Greetings

Scroll to Top