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
import java.io.*;
class ArrayFormat{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(n < 3 || n > 9){
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[] = new int[n];
int b[][] = new int[n][n];
System.out.println("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");
for(int i = 0; i < n; i++)
a[i] = Math.abs(Integer.parseInt(br.readLine()));
for(int i = 0; i < n; i++){
for(int j = 0; j < n - 1 - i; j++){
if(a[j] > a[j + 1]){
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
System.out.print("SORTED ARRAY:");
for(int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
int len = n;
for(int i = 0; i < n; i++){
int j = 0;
for(j = 0; j < len; j++)
b[i][j] = a[j];
int k = 0;
while(j < n){
b[i][j] = a[k];
j++;
k++;
}
len--;
}
System.out.println("FILLED MATRIX");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
}