Matrix Mirror Image Java Program | ISC Computer Science 2023 Paper 2

Write a program to declare a matrix A[][] of order (M × N) where ‘M’ is the number of rows and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than 10. Allow the user to input integers into this matrix. Display appropriate error message for an invalid input.

Perform the following tasks on the matrix:
(a) Display the input matrix
(b) Create and display the mirror image matrix
(c) Calculate the sum of the four corner elements of the matrix and display

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

Example 1
INPUT:
M = 3
N = 4

8793
-2045
136-4

OUTPUT:
ORIGINAL MATRIX

8793
-2045
136-4

MIRROR MATRIX

3978
540-2
-4631

SUM OF THE CORNER ELEMENTS = 8

Example 2
INPUT:
M = 2
N = 10
OUTPUT:
INVALID INPUT

import java.util.Scanner;
class MirrorImage{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("M = ");
        int m = Integer.parseInt(in.nextLine());
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        if(m < 3 || m > 9 || n < 3 || n > 9){
            System.out.println("INVALID INPUT");
            return;
        }
        int a[][] = new int[m][n];
        int sum = 0;
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                a[i][j] = Integer.parseInt(in.nextLine());
                if(i == 0){
                    if(j == 0 || j == n - 1)
                        sum += a[i][j];
                }
                else if(i == m - 1){
                    if(j == 0 || j == n - 1)
                        sum += a[i][j];
                }
            }
        }
        System.out.println("ORIGINAL MATRIX");
        display(a, m, n);
        for(int i = 0, j = n - 1; i < j; i++, j--){
            for(int k = 0; k < m; k++){
                int temp = a[k][i];
                a[k][i] = a[k][j];
                a[k][j] = temp;
            }
        }
        System.out.println("MIRROR MATRIX");
        display(a, m, n);
        System.out.println("SUM OF CORNER ELEMENTS = " + sum);
    }
    public static void display(int a[][], int m, int n){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *