Solved ISC practical 2021 Question 3
import java.util.*;
public class MatBoundSum
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no. of rows M and no. of columns N");
int M=sc.nextInt();
int N=sc.nextInt();
if(M>2&&M<8&&N>2&&N<8)//checking for the validity of M and N
{
int A[][]=new int[M][N];
System.out.println("Enter the elements of the matrix");
for(int i=0;i<M;i++)//taking input from the user
{
for(int j=0;j<N;j++)
{
A[i][j]=sc.nextInt();
}
}
int unsortsum=0;//sum of boundary elements of unsorted matrix
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
if(i==0||j==0||i==M-1||j==N-1)
{
unsortsum+=A[i][j];
}
}
}
System.out.println("ORIGINAL MATRIX");
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
System.out.print(A[i][j]+"\t");//Printing the matrix
}
System.out.println();
}
System.out.println("SUM OF BOUNDARY ELEMENTS(UNSORTED)="+unsortsum);
int arr[]=new int[M*N];//SDA for storing the matrix elements
int count=0;
for(int i=0;i<M;i++)//for storing the elements of A[][] in SDA arr
{
for(int j=0;j<N;j++)
{
arr[count]=A[i][j];
count++;
}
}//taking the matrix in SDA
//Now we will sort the SDA in descending order
for(int i=0;i<M*N-1;i++)
{
for(int j=0;j<M*N-i-1;j++)
{
if(arr[j]<arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}//orted the SDA named arr
int B[][]=new int[M][N];//another DDA for storing the sorted array
int countB=0;//another counter variable
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
B[i][j]=arr[countB];
countB++;
}
}//Putting the sorted array in matrix B
//Now we will find the sum of the boundary elements of sorted matrix
int sortsum=0;//for the sum of boundary elements of sorted matrix
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
if(i==0||j==0||i==M-1||j==N-1)
{
sortsum+=B[i][j];
}
}
}//Found the sum
System.out.println("SORTED MATRIX");
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
System.out.print(B[i][j]+"\t");
}
System.out.println();
}
System.out.println("SUM OF BOUNDARY ELEMENTS(SORTED)="+sortsum);
}//ending the if statement
else
System.out.println("OUT OF RANGE");
}//ending the main() function
}
Output:
Enter the no. of rows M and no. of columns N
3
4
Enter the elements of the matrix
11
2
-3
5
1
7
13
6
0
4
9
8
ORIGINAL MATRIX
11 2 -3 5
1 7 13 6
0 4 9 8
SUM OF BOUNDARY ELEMENTS(UNSORTED)=43
SORTED MATRIX
13 11 9 8
7 6 5 4
2 1 0 -3
SUM OF BOUNDARY ELEMENTS(SORTED)=52
Enter the no. of rows M and no. of columns N
3
3
Enter the elements of the matrix
6
2
5
14
1
17
9
4
8
ORIGINAL MATRIX
6 2 5
14 1 17
9 4 8
SUM OF BOUNDARY ELEMENTS(UNSORTED)=65
SORTED MATRIX
17 14 9
8 6 5
4 2 1
SUM OF BOUNDARY ELEMENTS(SORTED)=60
Enter the no. of rows M and no. of columns N
2
6
OUT OF RANGE
Enter the no. of rows M and no. of columns N
4
9
OUT OF RANGE
Related