Jump to content

Diagonal secundária de uma matriz


Serg1i

Recommended Posts

Olá malta programadora.

Estou a tirar um curso de programação. Estava a fazer um exercício de matrizes para apresentar no ecrã a diagonal principal. Depois tentei fazer o mesmo mas para a diagonal secundária no entanto tive de recorrer a um ciclo if como podem ver em baixo:

System.out.println();
System.out.print("Secondary diagonal: ");

 for (int i=0; i<n; i++){
       for (int j=0; j<n; j++){
             if(j+i == n-1){
                System.out.print(matriz [i] [j] + " ");
             } 
       }
 }

Funciona mas pretendo fazer somente com ciclos for:

A minha tentativa foi esta:

        System.out.println();
        System.out.print("Secondary diagonal: ");
        
        for (int i=0; i<n; i++){
            for (int j=n-1; j>=0; j--){
                System.out.print(matriz[i+j][i+j] + " ");
            }
        }

Imprime a diagonal secundária correctamente para o caso de uma matriz de 2x2 mas deu um erro de excepção -> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

Se for uma matriz 3x3 imprime a diagonal principal de cima para baixo e erro de excepção Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Alguém me pode dar uma dica?

Obrigado

Edited by Serg1i
Link to comment
Share on other sites

viva,

basta seguir o seu código e simular os 2 ciclos para uma matriz (n=3) 3x3:

i=0; j=2; print matriz[2][2]
i=0; j=1; print matriz[1][1]
i=0; j=0; print matriz[0][0]
i=1; j=2; print matriz[3][3] Index 3 out of bounds for length 3
i=1; j=1; print matriz[2][2]
i=1; j=0; print matriz[1][1]
i=2; j=2; print matriz[4][4] Index 4 out of bounds for length 3
i=2; j=1; print matriz[3][3] Index 3 out of bounds for length 3
i=2; j=0; print matriz[2][2]


cps,

Edited by antseq
Link to comment
Share on other sites

        System.out.println();
        System.out.print("Secondary diagonal: ");
        
        for (int i=0; i<n; i++){
            for (int j=n-1; j>=0; j--){
                System.out.print(matriz[i][j] + " ");
                i++;
            }
        }

Foi esta a solução que cheguei. Se alguém tiver uma outra alternativa agradeço a partilha

4 minutos atrás, antseq disse:

viva,

basta seguir o seu código e simular os 2 ciclos para uma matriz (n=3) 3x3:

i=0; j=2; print matriz[2][2]
i=0; j=1; print matriz[1][1]
i=0; j=0; print matriz[0][0]
i=1; j=2; print matriz[3][3] Index 3 out of bounds for length 3
i=1; j=1; print matriz[2][2]
i=1; j=0; print matriz[1][1]
i=2; j=2; print matriz[4][4] Index 4 out of bounds for length 3
i=2; j=1; print matriz[3][3] Index 3 out of bounds for length 3
i=2; j=0; print matriz[2][2]


cps,

Obrigado pelo esclarecimento 🙂

Edited by Serg1i
Link to comment
Share on other sites

4 horas atrás, Serg1i disse:

Foi esta a solução que cheguei. Se alguém tiver uma outra alternativa agradeço a partilha

Viva,

Estar a modificar a variável de um ciclo "for", a meio do procedimento para além do incremento (default já previsto) não é boa programação.
Se é para incrementar a torto e a direito utiliza um Do/While, faz então os incrementos que quiseres e validas no fim.

Sobre o seu problema, o mesmo pode ser simplificado num único "for":

     public static void main(String []args){
        int n=3;
        int matrix[][]={
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };
        System.out.println("Primary Diagonal");
        for(int k=0; k<n; k++)
            System.out.print(matrix[k][k] + " ");
        
        System.out.println("");
       
        System.out.println("Secondary Diagonal");
        for(int k=0; k<n; k++)
            System.out.print(matrix[k][n-1-k] + " ");             
     }
Output:
Primary Diagonal
1 5 9 
Secondary Diagonal
3 5 7 

cps,

Edited by antseq
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.