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

Asked

Viewed 1,044 times

1

Input example:

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

Output example:

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(); 
}

2 answers

3


Declare an array to store 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 quicker way if you only need the output.
Replace the output "for" 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 on Ideone

  • I guess I’d have to save the current value to a temporary variable to replace "on the other side"

  • I edited the answer

  • Thank you very much, it worked!

2

I prefer to go only once 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;
}

Browser other questions tagged

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