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 that both M and N must be greater than 2 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.
d) Output the rearranged matrix.
INPUT: M=3 N=4
Entered values:
8, 7, 9, 3, -2, 0, 4, 5, 1, 3, 6, -4
Original matrix:
8 7 9 3
-2 0 4 5
1 3 6 -4
Largest Number:
9 Row: 0 Column:
2
Smallest Number:
-4 Row=2 Column=3
Rearranged
matrix:
-4 -2 0 1
3 3 4 5
6 7 8 9
Input: M=3 N=22
Output: Size out of range
Solution:-
import java.util.*;
class matrix
{
int arr[][];
int
r,c,max,min,maxi,maxj,mini,minj,i,j,m,n;
void perform()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the
number of rows(M):");
r=sc.nextInt();
System.out.print("Enter the number
of columns(N):");
c=sc.nextInt();
if(r < 2 || c < 2 || r > 20 ||
c > 20)
System.out.println("Size out of
Range");
System.exit(0);
arr=new int[r][c];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print("Enter
Value:");
arr[i][j]=sc.nextInt();
}
}
max=arr[0][0];
min=arr[0][0];
maxi=0;
mini=0;
maxj=0;
minj=0;
for(i=0;i < r;i++)
{
for(j=0;j<c;j++)
{
if(arr[i][j]>max)
{
max=arr[i][j];
maxi=i;
maxj=j;
}
else if(arr[i][j]<min)
{
mini=i;
minj=j;
min=arr[i][j];
}
}
}
System.out.println("Original
Matrix");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.print("Maximum Value=
"+max);
System.out.print("\tRow=
"+maxi);
System.out.println("\tColumn=
"+maxj);
System.out.print("Minimum Value=
"+min);
System.out.print("\tRow=
"+mini);
System.out.println("\tColumn=
"+minj);
for(m=0;m< r;m++)
{
for(n=0;n< c;n++)
{
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
if(arr[m][n]<
arr[i][j])
{
min=arr[m][n];
arr[m][n]=arr[i][j];
arr[i][j]=min;
}
}
}
}
}
System.out.println("Rearranged
Matrix");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
System.out.print(arr[i][j]+"
");
}
System.out.println();
}
}
public static void main(String args[])
throws Exception
{
matrix ob=new matrix();
ob.perform();
}
}
No comments:
Post a Comment