Swap Diagonal Elements in a Matrix

Write a program in Java to allow the user to create a square matrix of size [M × M], where 3 < M < 10.

Display an appropriate error message if an invalid size of the matrix is entered.

For the valid matrix size, allow the user to fill this matrix with integers.

Display the original matrix.

Now swap all the elements of the left diagonal of this matrix with the right diagonal elements.

Display the resultant matrix.

Example:
INPUT:
M = 4
Original Matrix:

1     2     3    4
5     6     7    8
9    10   11   12
13   14   15   16

OUTPUT:
Resultant matrix:

4      2    3    1
5      7    6    8
9    11   10   12
16   14   15   13
import java.io.*;
class SwapDiagonal{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Square matrix size: ");
        int m = Integer.parseInt(br.readLine());
        if(m < 4 || m > 9){
            System.out.println("Size out of range!");
            return;
        }
        int a[][] = new int[m][m];
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Integer.parseInt(br.readLine());
            }
        }
        System.out.println("Original Matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        for(int i = 0, j = m - 1; i < m; i++, j--){
            int temp = a[i][j];
            a[i][j] = a[i][i];
            a[i][i] = temp;
        }
        System.out.println("Resultant Matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

2 thoughts on “Swap Diagonal Elements in a Matrix”

  1. Sir,a program is given which states that:
    The potential of a word is found by adding the ASCII value of the alphabets.
    (ASCII values of A to Z are 65 to 90).
    Example: BALL
    Potential = 66 + 65 + 76 + 76 = 283
    Write a program to accept a sentence which may be terminated by either “ . ” , “ ? ” or “ ! ” only.
    The words of sentence are separated by single blank space and are in UPPER CASE. Decode the
    words according to their potential and arrange them in ascending order of their potential strength.
    Test your program with the following data and some random data:
    Example 1:
    INPUT: HOW DO YOU DO?
    OUTPUT: HOW = 238
    DO = 147
    YOU = 253
    DO = 147
    DO DO HOW YOU
    How to solve this program using StringTokenizer?

Leave a Reply

%d bloggers like this: