How to sum the lines of a two-dimensional vector and show the result of the sum of each line?

Asked

Viewed 26 times

0

 for (int i = 0; i < vetor.length; i++) {
           for (int j = 0; j < vetor.length; j++) {
            soma += vetor[j][i];
           }
           System.out.print("Aluno " + (i + 1) + " : ");
           System.out.println(soma + " ");
       }
  • Only by one soma = 0 at the beginning of the first for

1 answer

0

If that’s what I understand, just reset the "sum" after reading each line, or save in a vector the sum of each line.

public class vetor {

    public static void main(String[] args) {

        int soma = 0;

        int vetor[][] = new int[5][5];

        for (int i = 0; i < vetor.length; i++) {
            for (int j = 0; j < vetor.length; j++) {
                vetor[i][j] = 1;
            }
        }
        
        for (int i = 0; i < vetor.length; i++) {
            for (int j = 0; j < vetor.length; j++) {
            soma+=vetor[i][j] = 1;
            }
            System.out.println(soma);
            soma=0;
        }
        
    }

}

case with vector:

public class vetor {

    public static void main(String[] args) {

        int soma[] = new int[5];

        int vetor[][] = new int[5][5];

        for (int i = 0; i < vetor.length; i++) {
            for (int j = 0; j < vetor.length; j++) {
                vetor[i][j] = 1;
            }
        }
        
        for (int i = 0; i < vetor.length; i++) {
            for (int j = 0; j < vetor.length; j++) {
            soma[i]+=vetor[i][j] = 1;
            }
            System.out.println(soma[i]);
        
        }
        
    }

}

Browser other questions tagged

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