How to invert the values of the main diagonal of a 5x5 matrix?

1

Example input:

  

1 3 6 8 7
  3 7 8 0 3
  2 4 3 6 7
  8 9 1 3 5
  5 6 7 8 5

Example output:

  

5 3 6 8 7
  3 3 8 9 3
  2 4 3 6 7
  8 0 1 7 5
  5 6 7 8 1

I have so far this:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int [][] Matriz = new int [5][5];
for(int i = 0; i<5; i++ ){ 
    for(int j=0; j<5; j++){ 
        System.out.println("introduce un valor para la posicion "+ i +", "+ j);
        try{ 
            Matriz[i][j]= Integer.parseInt(in.readLine()); 
        }catch (Exception e){
            e.printStackTrace(); 
        } 
    } 
} 
for(int i = 0; i<5; i++ ){
    for(int j=0; j<5; j++){
        System.out.print(Matriz[i][j]+" ");
    } 
    System.out.println(); 
}
    
asked by anonymous 09.04.2015 / 18:30

2 answers

3

Declare an array to keep the diagonal:

int [] diagonal = new int[5];

Between the input and output for, enter this code:

//Guarda diagonal
for(int i = 0; i<5; i++ ){
    diagonal[i] = Matriz[i][i];
}
//Repõe a diagonal na direção inversa
for(int i = 0; i<5; i++ ){
    Matriz[i][i] = diagonal[4-i];
}

See on Ideone

Another faster way if you only need output . Replace the "for" output with this:

for(int i = 0; i<5; i++ ){
    for(int j=0; j<5; j++){
        if(j==i){
            System.out.print(Matriz[4-i][4-j]+" ");
        }
        else
        {
            System.out.print(Matriz[i][j]+" ");
        }
    } 
    System.out.println();
}

See the Ideone

    
09.04.2015 / 19:16
2

I'd rather go only once in the following way:

int TAMANHO_MATRIZ = 5;

for(int i = 0; i<TAMANHO_MATRIZ/2; i++ ){
    int aux = Matriz[i][i]
    Matriz[i][i] = Matriz[TAMANHO_MATRIZ-i-1][TAMANHO_MATRIZ-i-1];
    Matriz[TAMANHO_MATRIZ-i-1][TAMANHO_MATRIZ-i-1] = aux;
}
    
09.04.2015 / 20:24