Question
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 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
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
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class RotateMatrix
{
public static void main(String args[])
{
int i=0,j=0,m=0,row=0,col=0,sum=0;
int arr[][],r[][];
Scanner sc=new Scanner(System.in);
System.out.print("M = ");
m = sc.nextInt();
if(m < 3 || m > 9)
{
System.out.println("SIZE OUT OF RANGE");
}
else
{
arr = new int[m][m];
System.out.println("Enter matrix elements:");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
arr[i][j] = sc.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
r = new int[m][m];
row = 0;
col = m - 1;
for(i = 0; i < m; i++)
{
row = 0;
for(j = 0; j < m; j++)
{
r[row][col] = arr[i][j];
row++;
}
col--;
}
System.out.println("MATRIX AFTER ROTATION");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
System.out.print(r[i][j] + "\t");
}
System.out.println();
}
sum = arr[0][0] + arr[0][(m-1)] + arr[(m-1)][0] + arr[(m-1)][(m-1)];
System.out.println("Sum of the corner elements = " + sum);
}
}
}
Coding Store
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale
