Fill Matrix Java Program | ISC Computer Science 2019 Practical

Write a program to declare a single dimensional array a[] and a square matrix b[][] of size N, where N > 2 and N < 10. Allow the user to input positive integers into the single-dimensional array.

Perform the following tasks on the matrix:
(a) Sort the elements of the single dimensional array in ascending order using any standard sorting technique and display the sorted elements.
(b) Fill the square matrix b[][] in the following format:
If the array a[] = {5, 2, 8, 1} then, after sorting a[] = {1, 2, 5, 8}
Then, the matrix b[][] would fill as below:
1 2 5 8
1 2 5 1
1 2 1 2
1 1 2 5
(c) Display the filled matrix in the above format.

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

Example 1
INPUT:
N = 3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX
1 3 7
1 3 1
1 1 3

Example 2
INPUT:
N = 13
OUTPUT:
MATRIX SIZE OUT OF RANGE

Example 3
INPUT:
N = 5
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 10 2 5 23 6
OUTPUT:
SORTED ARRAY: 2 5 6 10 23
FILLED MATRIX

2561023
256102
25625
25256
225610
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());
        int a[] = new int[n];
        int b[][] = new int[n][n];
        System.out.println("ENTER ARRAY ELEMENTS:");
        for(int i = 0; i < n; i++)
            a[i] = Integer.parseInt(in.nextLine());
        sort(a);
        System.out.print("SORTED ARRAY: ");
        for(int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
        int limit = n - 1;
        for(int i = 0; i < n; i++){
            for(int j = 0; j <= limit; j++)
                b[i][j] = a[j];
            int index = 0;
            for(int k = limit + 1; k < n; k++)
                b[i][k] = a[index++];
            limit--;
        }
        System.out.println("\nFILLED MATRIX");
        display(b);
    }
    public static void sort(int a[]){
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length - 1 - i; j++){
                if(a[j] > a[j + 1]){
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
    public static void display(int a[][]){
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length; 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 *