Sum of the elements of the secondary diagonal of a matrix

Asked

Viewed 1,084 times

0

I made a program that the user declares the size of the matrix, and the matrix numbers are random. But in the sum part does not work and displays many errors.

Java
    public  static  void  main ( String[] args ) {
        Random aleatorio = new Random();
        
        Scanner input = new Scanner(System.in);
        System.out.print("Digite o numero de linhas da matriz:\n ");
        int linha = input.nextInt();
        System.out.print("Digite o numero de colunas da matriz:\n ");
        int coluna = input.nextInt();

        int[][] matriz = new int[linha][coluna];
        for (int i = 0; i < matriz.length; i++){
            matriz[linha][coluna] = aleatorio.nextInt(9);
        }
        System.out.printf("%d ", matriz[linha][coluna]);
    
        //Essa parte não funciona
        public static int somaDiagonal(matriz [][]) {
        int soma = 0;
        coluna = matriz.length - 1;
        for (linha = 0; linha < matriz.length; linha++){
           soma += matriz[linha][coluna];
           coluna--;
           }
        return soma;
        }
    }

1 answer

1


I don’t know if it was a typo, but you created the method somaDiagonal within of the method main. Forget it. Or create a method outside the main, or do not use the method and put all the code in itself main.

Another detail is that the for to fill the matrix is wrong. You are going from first to last line, and always setting matriz[linha][coluna] (that is, it is always trying to change the same position). Another detail is that linha is the number of rows, but the matrix indexes range from zero to linha - 1, then when trying to access the position linha, make a mistake.

Actually you have to do two for nested (one for rows, one for columns) and fill each position.

Remember that there are actually no actual matrices in Java. What we have are arrays of arrays: an array in which each element is another array. The difference is that each one of these arrays can have a different size, and it is up to the programmer to control it so that they all have the same size (in an array, all rows must have the same number of columns, as is done in C#, for example - see here the difference).

In this case it is well controlled, so I will not include the size checks. But anyway, to fill the matrix would be something like this:

for (int i = 0; i < matriz.length; i++) {
    for (int j = 0; j < matriz[i].length; j++) {
        matriz[i][j] = aleatorio.nextInt(9);
        System.out.printf("%d ", matriz[i][j]);
    }
}

Notice how I fill the position [i][j], for i and j vary in the loop - i.e., at each iteration I am filling a different position (making [linha][coluna], you were always trying to change the same position, since the values of linha and coluna did not vary).


For the secondary diagonal, you have to start with the last element of the first line, then the penultimate of the second line, and so on. But remember that if the matrix is not square, you have to stop when finishing the rows or columns. For example, in a 2 x 4 matrix:

1 2 3 4
5 6 7 8

The secondary diagonal is numbers 4 and 7.

Already in a 4 x 2 matrix:

1 2
3 4
5 6
7 8

The secondary diagonal is numbers 2 and 3.

Anyway, I’d be like this:

public static void main(String[] args) {
    Random aleatorio = new Random();

    Scanner input = new Scanner(System.in);
    System.out.print("Digite o numero de linhas da matriz:\n ");
    int linha = input.nextInt();
    System.out.print("Digite o numero de colunas da matriz:\n ");
    int coluna = input.nextInt();

    int[][] matriz = new int[linha][coluna];
    for (int i = 0; i < matriz.length; i++) {
        for (int j = 0; j < matriz[i].length; j++) {
            matriz[i][j] = aleatorio.nextInt(9);
            System.out.printf("%d ", matriz[i][j]);
        }
        System.out.println();
    }

    System.out.println("Soma da diagonal secundária=" + somaDiagonal(matriz));
}

// crie o método fora do main
public static int somaDiagonal(int[][] matriz) {
    int soma = 0;
    int coluna = matriz[0].length - 1; // último elemento da primeira linha
    for (int linha = 0; linha < matriz.length; linha++) {
        soma += matriz[linha][coluna];
        coluna--;
        if (coluna < 0) // acabaram as colunas, interrompe o for
            break;
    }
    return soma;
}

A detail that "many people" forget is that in the condition of for you can put anything (not only valor < tamanho, that although it is the most common, it is not the only possibility). The same goes for the other parts: I can initialize both variables at once, and put the column decrement together with the row increment. Would look like this:

public static int somaDiagonal(int[][] matriz) {
    int soma = 0;
    for (int linha = 0, coluna = matriz[0].length - 1; linha < matriz.length && coluna >= 0; linha++, coluna--) {
        soma += matriz[linha][coluna];
    }
    return soma;
}
  • Thanks @hkotsubo, it worked now :) .

Browser other questions tagged

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