How to get the number of rows and columns in a matrix

0

my question is the following, I want to get the number of rows and columns of my matrix , to print its content on screen, but in the for no I want to place i < (number of elements that you put), I would like something like i < rows.length

int numeros[][] = new int [2][3];

    numeros[0][0] = 100;
    numeros[0][1] = 200;
    numeros[0][2] = 300;

    numeros[1][0] = 400;
    numeros[1][1] = 500;
    numeros[1][2] = 600;

    for (int f = 0; f < 2 <=(**Aqui es donde me refiero**); f++) {

        for (int c = 0; c < 3 <=(**Aqui es donde me refiero**); c++) {

            System.out.print(numeros[f][c] + " ");

        }

        System.out.println();
    }
    
asked by darioxlz 27.12.2017 в 21:30
source

2 answers

0

You can use the following code:

int numeros[][] = new int [2][3];

numeros[0][0] = 100;
numeros[0][1] = 200;
numeros[0][2] = 300;

numeros[1][0] = 400;
numeros[1][1] = 500;
numeros[1][2] = 600;

for (int f = 0; f < numeros.length; f++) {

   for (int c = 0; c < numeros[f].length; c++) {

       System.out.print(numeros[f][c] + " ");

   }

   System.out.println();
}

numeros.length stores the number of rows in the matrix and numeros[f].length when f is zero we access the number of elements in row zero and so on for each value of f

    
answered by 27.12.2017 / 21:39
source
0

First, in java when defining a matrix like the one you have defined, always create an array of [rows] x [columns] this is done by performance issues in cache, in this way your program is more efficient to bring the rows in contiguous blocks (columns belonging to said row) that is what you are going to go through.

  

To get the rows you only need: numeros.length

     

To obtain the number of columns belonging to that row:    numeros[i].length

Example:

int numeros[][] = new int [2][3];

numeros[0][0] = 100;
numeros[0][1] = 200;
numeros[0][2] = 300;

numeros[1][0] = 400;
numeros[1][1] = 500;
numeros[1][2] = 600;

System.out.print("Numero de filas: "+numeros.length);
for (int i = 0; i < numeros.length; i++) {
   System.out.print("Fila "+ i + " contiene :" + numeros[i].length + "columnas");
}

Note: You have initialized the values of your matrix in its entirety, but you have to bear in mind that if you do not initialize any value this will be initialized to 0 by default, this is important since if you are interested in knowing how many fields in the matrix have really filled in, you'll have to make a comparison with 0.

    
answered by 28.12.2017 в 09:12