ISC practical papers › ISC 2015 › Question 2
Rotation of Matrix
ISC 2015 Computer Science Practical, Question 2 · Arrays and matrices
The question
Write a program to declare a square matrix A[][] of order M x 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 the matrix. Perform the following tasks: a) Display the original matrix. b) Rotate the matrix 90o 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 corners of the matrix.
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 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 OUTPUT: SIZE OUT OF RANGE
Question: ISC 2015 Computer Science Paper 2 (Practical), Question 2, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Matrix {
private int A[][], M;
public Matrix(int M) {
A = new int[M][M];
this.M = M;
}
public void getInput() {
Scanner in = new Scanner(System.in);
for (int row = 0; row < M; row++) {
for (int col = 0; col < M; col++) {
A[row][col] = in.nextInt();
}
}
in.close();
}
public String toString() {
String output = "";
for (int row = 0; row < M; row++) {
output += "\t";
for (int col = 0; col < M; col++) {
output += A[row][col];
if (col < M)
output += "\t";
}
output += "\n";
}
return output;
}
public void rotate() {
int half = M / 2, temp;
for (int i = 0; i < half; i++) {
for (int x = i; x < M - i - 1; x++) {
temp = A[M - x - 1][i];
A[M - x - 1][i] = A[M - i - 1][M - x - 1];
A[M - i - 1][M - x - 1] = A[x][M - i - 1];
A[x][M - i - 1] = A[i][x];
A[i][x] = temp;
}
}
}
public int getCornerSum(){
return A[0][0]+A[0][M-1]+A[M-1][M-1]+A[M-1][0];
}
}
public class ISC2015Q2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("INPUT:\tM = ");
int M = in.nextInt();
if (M > 2 && M < 10) {
Matrix objMatrix = new Matrix(M);
objMatrix.getInput();
System.out.println("OUTPUT:");
System.out.println("ORIGINAL MATRIX");
System.out.println(objMatrix);
objMatrix.rotate();
System.out.println("MATRIX AFTER ROTATION");
System.out.println(objMatrix);
System.out.println("Sum of the corner elements = "+objMatrix.getCornerSum());
} else {
System.out.println("OUTPUT: SIZE OUT OF RANGE");
}
in.close();
}
}
All these solutions in one free book
Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.