Rotate Matrix 90° Clockwise Java Program | ISC Computer Science 2015 Paper 2

Write a program to declare a square matrix a[][] of order m × m where ‘m’ is the number of rows and the number of columns, such that m must be greater than 2 and less than 10. Accept the value of m as user input. Allow the user to input integers into this matrix. Perform the following tasks:

1. Display the original matrix.
2. Rotate the matrix 90° clockwise as shown below:
Original matrix:
1 2 3
4 5 6
7 8 9
Rotated matrix:
7 4 1
8 5 2
9 6 3
3. Find the sum of the elements of the four corners of the matrix.

Test your program with the sample data and some random data:

Example 1:
INPUT: m = 3
3 4 9
2 5 8
1 6 7
OUTPUT:
ORIGINAL MATRIX:
3 4 9
2 5 8
1 6 7
MATRIX AFTER ROTATION:
1 2 3
6 5 4
7 8 9
Sum of the corner elements = 20

Example 2:
INPUT: m = 4
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
OUTPUT:
ORIGINAL MATRIX:
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
MATRIX AFTER ROTATION:
3 1 2 1
7 6 5 2
6 7 8 4
5 4 3 9
Sum of the corner elements = 18

Example 3:
INPUT: m = 14
SIZE OUT OF RANGE

import java.util.Scanner;
class Rotate{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("m = ");
        int m = Integer.parseInt(in.nextLine());
        if(m < 3 || m > 9){
            System.out.println("SIZE OUT OF RANGE");
            return;
        }
        int a[][] = new int[m][m];
        int b[][] = 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(in.nextLine());
            }
        }
        System.out.println("ORIGINAL MATRIX:");
        display(a);
        int q = m - 1;
        for(int i = 0; i < m; i++){
            int p = 0;
            for(int j = 0; j < m; j++){
                b[p++][q] = a[i][j];
            }
            q--;
        }
        System.out.println("MATRIX AFTER ROTATION:");
        display(b);
        int sum = b[0][0] + b[0][m - 1] + b[m - 1][0] + b[m - 1][m - 1];
        System.out.println("Sum of the corner elements = " + sum);
    }
    public static void display(int mat[][]){
        for(int i = 0; i < mat.length; i++){
            for(int j = 0; j < mat.length; j++){
                System.out.print(mat[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

One thought on “Rotate Matrix 90° Clockwise Java Program | ISC Computer Science 2015 Paper 2

Leave a Reply

Your email address will not be published. Required fields are marked *