Fill Matrix 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
OUTPUT:
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
class Matrix{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n < 3 || n > 9){
System.out.println("MATRIX SIZE OUT OF RANGE");
return;
}
int a[] = new int[n];
System.out.println("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");
for(int i = 0; i < a.length; i++)
a[i] = Integer.parseInt(in.nextLine());
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;
}
}
}
System.out.print("SORTED ARRAY: ");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
int m[][] = new int[n][n];
int row = 0;
int col = 0;
for(int i = m.length - 1; i >= 0; i--){
col = 0;
int j;
for(j = 0; j <= i; j++){
m[row][col] = a[j];
col++;
}
int k = 0;
for(; j < a.length; j++)
m[row][j] = a[k++];
row++;
}
System.out.println("\nFILLED MATRIX");
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++)
System.out.print(m[i][j] + "\t");
System.out.println();
}
}
}
Comments
Post a Comment