Categories

# Rotate Matrix ISC 2015 Practical

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. Display an appropriate message for an invalid input. Allow the user to input integers into this matrix. Perform the following tasks:

(a) Display the original matrix.
(b) Rotate the matrix 90o clockwise as shown below:

`Original matrix        Rotated matrix1 2 3                  7 4 14 5 6                  8 5 27 8 9                  9 6 3`

(c) Find the sum of the elements of the four corners of the matrix.

Test your program for the following data and some random data:

Example 1:
INPUT:
M = 3

`3    4    92    5    81    6    7`

OUTPUT:
ORIGINAL MATRIX

`3    4    92    5    81    6    7`

MATRIX AFTER ROTATION

`1    2    36    5    47    8    9`

Sum of the corner elements = 20

Example 2:
INPUT:
M = 4

`1    2    4    92    5    8    31    6    7    43    7    6    5`

OUTPUT:

ORIGINAL MATRIX

`1    2    4    92    5    8    31    6    7    43    7    6    5`

MATRIX AFTER ROTATION

`3    1    2    17    6    5    26    7    8    45    4    3    9`

Sum of the corner elements = 18

Example 3:
INPUT:
M = 14
OUTPUT:
SIZE OUT OF RANGE

``````import java.io.*;
class Rotate{
public static void main(String args[])throws IOException{
System.out.print("M = ");
if(m < 3 || 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++){
}
}
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();
}
int r[][] = new int[m][m];
int row = 0; int col = m - 1;
for(int i = 0; i < m; i++){
row = 0;
for(int j = 0; j < m; j++){
r[row++][col] = a[i][j];
}
col--;
}
System.out.println("MATRIX AFTER ROTATION");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
System.out.print(r[i][j] + "\t");
}
System.out.println();
}
int last = m - 1;
int sum = a[0][0] + a[0][last] + a[last][0] + a[last][last];
System.out.println("Sum of the corner elements = " + sum);
}
}``````