Fill Matrix with Characters Program in Java | ISC Computer Science 2023 Paper 2

Write a program to declare a square matrix M[][] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Accept the value of N as user input. Display an appropriate message for an invalid input. Allow the user to accept three different characters from the keyboard and fill the matrix according to the instruction given below:

(i) Fill the four corners of the square matrix by character 1
(ii) Fill the boundary elements of the matrix (except the four corners) by character 2
(iii) Fill the non-boundary elements of the matrix by character 3
(iv) Display the matrix formed by the above instructions

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

Example 1
INPUT:
N = 4
Enter first character: @
Enter second character: ?
Enter third character: #
OUTPUT:
FORMED MATRIX

@??@
?##?
?##?
@??@

Example 2
INPUT:
N = 5
Enter first character: A
Enter second character: C
Enter third character: X
OUTPUT:
FORMED MATRIX

ACCCA
CXXXC
CXXXC
CXXXC
ACCCA

Example 3
INPUT: N = 12
OUTPUT: SIZE OUT OF RANGE

import java.util.Scanner;
class FillMatrix{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        if(n < 4 || n > 9){
            System.out.println("SIZE OUT OF RANGE");
            return;
        }
        char m[][] = new char[n][n];
        System.out.print("Enter first character: ");
        char a = in.nextLine().charAt(0);
        System.out.print("Enter second character: ");
        char b = in.nextLine().charAt(0);
        System.out.print("Enter third character: ");
        char c = in.nextLine().charAt(0);
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(i == 0 || i == n - 1){
                    if(j == 0 || j == n - 1)
                        m[i][j] = a;
                    else
                        m[i][j] = b;
                }
                else if(i == 0 || j == 0 || i == n - 1 || j == n - 1)
                    m[i][j] = b;
                else
                    m[i][j] = c;
            }
        }
        System.out.println("FORMED MATRIX");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++)
                System.out.print(m[i][j] + "\t");
            System.out.println();
        }
    }
}

Leave a Reply

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