Question
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
2 5 6 10 23
2 5 6 10 2
2 5 6 2 5
2 5 2 5 6
2 2 5 6 10
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class arraySort
{
public static void main(String args[])
{
int i=0,j=0,k=0,len=0,n=0,temp=0;
int a[],b[][];
Scanner sc=new Scanner(System.in);
System.out.print("N = ");
n = sc.nextInt();
if(n < 3 || n > 9)
{
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
a= new int[n];
b= new int[n][n];
System.out.println("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");
for(i = 0; i < n; i++)
{
a[i] = Math.abs(sc.nextInt());
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("SORTED ARRAY:");
for(i = 0; i < n; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
len = n;
for(i = 0; i < n; i++)
{
j = 0;
for(j = 0; j < len; j++)
{
b[i][j] = a[j];
}
k = 0;
while(j < n)
{
b[i][j] = a[k];
j++;
k++;
}
len--;
}
System.out.println("FILLED MATRIX");
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
}