118k views
11 votes
Write a program to declare a matrix A[][] of order (MXN) where ‘M’ is the number of rows and ‘N’ is the

number of columns such M and N must be
greater than w and less than 20. Allow the user to input





integers into this matrix. Perform the following tasks on the matrix:
(a) Display the input matrix
(b) Find the maximum and minimum value in the matrix and display them along with their position.
(c) Sort the elements of the matrix in ascending order using any standard sorting technique and rearrange them in the matrix.

Can anybody show the program and explain please
Urgent.

User Dcook
by
5.2k points

1 Answer

5 votes

Answer:

import java.io.*;

import java.util.Arrays;

class Main {

public static void main(String args[])

throws IOException{

// Set up keyboard input

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(in);

// Prompt for dimensions MxN of the matrix

System.out.print("M = ");

int m = Integer.parseInt(br.readLine());

System.out.print("N = ");

int n = Integer.parseInt(br.readLine());

// Check if input is within bounds, exit if not

if(m <= 2 || m >= 10 || n <= 2 || n >= 10){

System.out.println("Matrix size out of range.");

return;

}

// Declare the matrix as two-dimensional int array

int a[][] = new int[m][n];

// Prompt for values of the matrix elements

System.out.println("Enter elements of matrix:");

for(int i = 0; i < m; i++){

for(int j = 0; j < n; j++){

a[i][j] = Integer.parseInt(br.readLine());

}

}

// Output the original matrix

System.out.println("Original Matrix:");

printMatrix(a);

// Sort each row

for(int i = 0; i < m; i++){

Arrays.sort(a[i]);

}

// Print sorted matrix

System.out.println("Matrix after sorting rows:");

printMatrix(a);

}

// Print the matrix elements separated by tabs

public static void printMatrix(int[][] a) {

for(int i = 0; i < a.length; i++){

for(int j = 0; j < a[i].length; j++)

System.out.print(a[i][j] + "\t");

System.out.println();

}

}

}

Step-by-step explanation:

I fixed the mistake in the original code and put comments in to describe each section. The mistake was that the entire matrix was sorted, while only the individual rows needed to be sorted. This even simplifies the program. I also factored out a printMatrix() method because it is used twice.

User Andrey Bushman
by
4.3k points