Fill in a matrix and add up your numbers

Asked

Viewed 1,000 times

0

I need to make a program (MATRIX) that performs the sum of all elements of a 10x10 matrix, containing integers.

But I’m not able to add or put values in all elements of the matrix.

As I do not use much matrix I do not understand very well the functioning. My code:

public class Exercicio {

    public static void main(String[] args) {
        int matriz [][] = new int [10] [10];
        int linha;
        int coluna;
        int resultado;

        for (linha = 0; linha >=10; linha++)
        {
            for (coluna = 0; coluna >= 10; coluna++)
            {
            }
        }
        //Não consegui colocar valores nas posições da linha e nem da coluna 

        resultado = matriz [linha] + matriz[coluna];
        System.out.println (resultado);

    }

}
  • You don’t need to put "solved" in the title. I know that in many forums it is common to do this, but you don’t need it here. You have already accepted the answer below and that is enough for others to know that the problem has been solved.

2 answers

1


Daniel,

Your loop is incorrect, you start at 0 and go until the row is smaller than the matrix size, the same is repeated with the column:

for( int linha = 0; linha < matriz.length; linha++) {
    for( int coluna = 0; coluna < matriz[linha].length; coluna++) {
    }
}

Your sum line of the results should be inside the loop, and it should not add the positions, it should only take the value and add to its result:

resultado += matriz [linha][coluna];

It may also be as follows::

resultado = resultado + matriz[linha][coluna];

Making the corrections in your code, it would be more or less as follows:

public class Exercicio {
  public static void main(String[] args) {
    int matriz[][] = new int[10][10];
    int soma = 0;

    //Laço responsável por preencher a matriz com números quaisquer
    for( int linha = 0; linha < matriz.length; linha++) {
      for( int coluna = 0; coluna < matriz[linha].length; coluna++) {
        //Gera um numero qualquer para a matriz
        matriz[linha][coluna] = linha * coluna;
      }
    }

    //Laço responsável por efetuar a soma de todos os valores presentes na matriz
    for( int linha = 0; linha < matriz.length; linha++) {
      for( int coluna = 0; coluna < matriz[linha].length; coluna++) {
        soma += matriz[linha][coluna];
      }
    }

    System.out.println(soma);
  }
}

See that I made a loop only to generate values, you can generate the values in several ways, this is just an example.

  • Thank you very much, as I had spoken I do not move much with matrices, apparently it was a basic error, I did not know that the sum was being performed in the wrong way ;-;,

0

An alternative to summing the values of the matrix is to use the Enhanced for (which some call "foreach"):

int matriz[][] = new int[10][10];
...
// assumindo que a matriz já está com os valores preenchidos
int soma = 0;
for (int[] linha : matriz) {
    for (int valor : linha) {
        soma += valor;
    }
}

There are no actual matrices in Java, and to simulate them we can use arrays of arrays. So matriz is actually an array, and every element of it is another array (and nothing prevents the "lines" of the "matrix" from being of different sizes).

So in the first for I declare int[] linha, because each element of the matrix is an array of int (one int[]). Then just go through this array with another for, where each element is one int.


This syntax has a limitation, which is not having access to the indexes. So you couldn’t use it to fill the values of the matrix. That is, the code below does not work:

for (int[] linha : matriz) {
    for (int valor : linha) {
        valor = 1; // NÃO FUNCIONA, o valor da matriz não é alterado
    }
}

In this case, the only way is to make one for traditional, as per the answer from Daniel. But if you just want to access the values, without needing the index, the Enhanced for is an alternative.


Another alternative to summing the values, if using Java >= 8, is to use streams:

int soma = Arrays.stream(matriz).flatMapToInt(linha -> Arrays.stream(linha)).sum();

Arrays.stream converts the matriz for a stream of int[], and flatMapToInt converts each row of the matrix (i.e., each int[]) for a IntStream. The result is a IntStream containing all matrix numbers.

Finally, the method sum() returns the sum of all numbers.

It is worth remembering that in this case, maybe it is exaggerated to use streams, for they have their cost and are slower than a loop traditional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.