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 20. Allow the user to input integers into this matrix. Display appropriate error message for an invalid input. Perform the following tasks:
- Display the input matrix.
- Create a mirror image of the inputted matrix.
- Display the mirror image matrix.
Test your program for the following data and some random data:
Example 1:
INPUT : M = 3
4 16 12
8 2 14
6 1 3
OUTPUT :
ORIGINAL MATRIX
4 16 12
8 2 14
6 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 6
Example 2:
INPUT : M = 22
OUTPUT : SIZE OUT OF RANGE
import java.util.*;
class ISCPrac2013Q2{
public static void main(String[]args)throws InputMismatchException
{
int M, i, j, k, t;
Scanner scan = new Scanner(System.in);
System.out.println("Enter no of rows for a square matrix: ");
M= scan.nextInt();
if(M<=2 || M>=20){
System.out.println("\nSIZE OUT OF RANGE");
}else{
int A[][] = new int [M][M];
System.out.println("Enter "+(M*M) + " elements: ");
for(i=0;i < M;i++){
for(j=0;j < M;j++){
A[i][j] = scan.nextInt();
}
}
//DISPLAY THE ORIGINAL MATRIX
System.out.println("ORIGINAL MATRIX");
for(i=0;i < M;i++){
for(j=0;j < M;j++){
System.out.print(A[i][j]+" ");
}
System.out.println();
}
//USE TWO COUNTERS FOR ACCESSING COLUMNS -
// ONE INCREMENTAL, ONE DECREMENTAL
for(j=0, k = M-1; j < M/2; j++, k--){
for(i=0;i < M; i++){
//SWAP THE ELEMENTS OF THE FIRST COLUMN WITH THE LAST,
//SECOND COLUMN WITH SECOND LAST AND SO ON
t = A[i][j];
A[i][j] = A[i][k];
A[i][k] = t;
}
}
//DISPLAY THE MIRROR IMAGE MATRIX
System.out.println("ORIGINAL MATRIX");
for(i=0;i < M;i++){
for(j=0;j < M;j++){
System.out.print(A[i][j]+" ");
}
System.out.println();
}
}//END OF ELSE
}//END OF MAIN
}//END OF CLASS
Have something to say? Log in to comment on this post.
0 comments