Write a program to declare a square matrix A[][] of order MxM where
‘M’ is the number of rows and the number of coloumns, such that M is greater than 2 and less than 10. Accept the value of M as user input. Display an appropriate message for invalid input. Allow the user to input integers into this matrix. Perform the following tasks:
(a) Display the original matrix.
(b) Rotate the matrix 90 degree clockwise as shown below:
Original matrix Rotated matrix 1 2 3 7 4 1 4 5 6 8 5 2 7 8 9 9 6 3
(c) Find the sum of the elements of the four corner elements.
Test your program for the following 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 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 corner elements = 18
Example 3
INPUT: M = 14 OUTPUT: SIZE IS OUT OF RANGE
The Java implementation for “Rotation of matrix by 90 degree clockwise” is as follows:
import java.util.*; class Q2{ public static int[][] rotate( int a[][] ){ int n=a.length; int temp; for (int i=0; i<n/2; i++){ for (int x=i; x<n-i-1; x++){ temp=a[n-x-1][i]; a[n-x-1][i]=a[n-i-1][n-x-1]; a[n-i-1][n-x-1]=a[x][n-i-1]; a[x][n-i-1]=a[i][x]; a[i][x]=temp; } } return a; } public static void displayArray( int ar[][] ){ for(int row=0; row<ar.length; row++){ for( int col=0; col<ar[row].length;col++){ System.out.print(ar[row][col]+"\t"); } System.out.println(); } } public static void main( String args[] ){ Scanner sc = new Scanner( System.in ); System.out.print("INPUT:\tM = "); int M = sc.nextInt(); if( M>2 && M<10 ){ int A[][] = new int[M][M]; for(int row=0; row<A.length; row++){ for( int col=0; col<A[row].length;col++){ A[row][col]=sc.nextInt(); } } System.out.println("OUTPUT:\nORIGINAL MATRIX"); displayArray(A); A = rotate(A); System.out.println("OUTPUT:\nMATRIX AFTER ROTATION"); displayArray(A); int cornerSum = A[0][0]+A[0][M-1]+A[M-1][0]+A[M-1][M-1]; System.out.println("Sum of corner elements = " + cornerSum); }else{ System.out.println("OUTPUT:\nSIZE OUT OF RANGE"); } } }
In the above program on “Rotation of matrix by 90 degree clockwise” was asked in the ISC Computer Practical 2015.