C Programs Tutorials | IT Developer
IT Developer

Java Programs - Solved 2018 Practical Paper ISC Computer Science



Share with a Friend

Solved 2018 Practical Paper ISC Computer Science

Class 12 - ISC Computer Science Solved Practical Papers

Sorting Two-Dimensional Matrix Program - ISC 2018 Practical

Write a program to declare a matrix a[][] of order (m × n) where ‘m’ is the number of rows and ‘n’ is the number of columns such that the values of both ‘m’ and ‘n’ must be greater than 2 and less than 10. Allow the user to input integers into this matrix. Perform the following tasks on the matrix:

  • Display the original matrix.
  • Sort each row of the matrix in ascending order using any standard sorting technique.
  • Display the changed matrix after sorting each row.

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

Example 1:
INPUT:
m = 4
n = 3
Enter elements of matrix:

11   -2    3
5    16    7
9    0     4
3    1     8

OUTPUT:
Original Matrix:

11   -2    3
5    16    7
9    0     4
3    1     8

Matrix after sorting rows:

-2    3    11
5     7    16
0     4     9
1     3     8

Example 2:
INPUT:
m = 3
n = 3
Enter elements of matrix:

22    5    19
7     36   12
9     13   6

OUTPUT:
Original matrix:

22    5    19
7     36   12
9     13   6

Matrix after sorting rows:

5     19   22
7     12   36
6     9    13

Example 3:
INPUT:
m = 11
n = 5
OUTPUT:
Matrix size out of range.

Program:

import java.io.*; class MatrixSort{ public static void main(String args[]) throws IOException{ InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); int m = 0; int n = 0; int a[][]; int i = 0; int j = 0; int temp[]; int k = 0; System.out.print("M = "); m = Integer.parseInt(br.readLine()); System.out.print("N = "); n = Integer.parseInt(br.readLine()); if(m <= 2 || m >= 10 || n <= 2 || n >= 10){ System.out.println("Matrix size out of range."); return; } a = new int[m][n]; temp = new int[m * n]; System.out.println("Enter elements of matrix:"); for(i = 0; i < m; i++){ for(j = 0; j < n; j++){ a[i][j] = Integer.parseInt(br.readLine()); temp[k++] = a[i][j]; } } System.out.println("Original Matrix:"); for(i = 0; i < m; i++){ for(j = 0; j < n; j++) System.out.print(a[i][j] + "\t"); System.out.println(); } for(i = 0; i < temp.length; i++){ for(j = 0; j < temp.length - 1 - i; j++){ if(temp[j] > temp[j + 1]){ int t = temp[j]; temp[j] = temp[j + 1]; temp[j + 1] = t; } } } k = 0; for(i = 0; i < m; i++) for(j = 0; j < n; j++) a[i][j] = temp[k++]; System.out.println("Matrix after sorting rows:"); for(i = 0; i < m; i++){ for(j = 0; j < n; j++) System.out.print(a[i][j] + "\t"); System.out.println(); } } }

Output

OUTPUT :
 
M = 4
N = 3
Enter elements of matrix:
1
5
7
2
9
10
3
11
4
12
6
8
Original Matrix:
1   5   7   
2   9   10  
3   11  4   
12  6   8   
Matrix after sorting rows:
1   2   3   
4   5   6   
7   8   9   
10  11  12