**Question:**

Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3 and less than 10. Allow the user to input positive integers into this matrix. Perform the following tasks on the matrix:

(a) Sort the boundary elements in descending order using any standard sorting technique and rearrange them in the matrix.

(b) Calculate the sum of the boundary elements.

(c) Display the original matrix, rearranged matrix and sum of the boundary elements.

Test your program with the sample data and some random data:

**Example 1**

**INPUT :**M = 4

9 2 1 5 8 13 8 4 15 6 3 11 7 12 23 8

**OUTPUT:**

**ORIGINAL MATRIX**

9 2 1 5 8 13 8 4 15 6 3 11 7 12 23 8

**REARRANGED MATRIX**

23 15 12 11 1 13 8 9 2 6 3 8 4 5 7 8 The sum of boundary elements is = 105

**Programming Code:**

/**The class SortBoundary, sorts the boundary elements of a 2-D square matrix in descending order. * It also finds the sum of the boundary elements * @author : www.guideforschool.com * @Program Type : BlueJ Program - Java */ import java.util.*; class SortBoundary { int A[][], B[], m, n; static int sum=0; void input() //Function for taking all the necessary inputs { Scanner sc = new Scanner(System.in); System.out.print("Enter the size of the square matrix : "); m=sc.nextInt(); if(m<4 || m>10) { System.out.println("Invalid Range"); System.exit(0); } else { A = new int[m][m]; n = m*m; B = new int[n]; // 1-D Array to store Boundary Elements System.out.println("Enter the elements of the Matrix : "); for(int i=0;iB[j] { c = B[i]; B[i] = B[j]; B[j] = c; } } } } /* Function fillSpiral is filling the boundary of 2-D array in spiral * way from the elements of 1-D array */ void fillSpiral() { int R1=0, R2=m-1, C1=0, C2=m-1, x=0; for(int i=C1;i<=C2;i++) // accessing the top row { A[R1][i]=B[x++]; } for(int i =R1+1;i<=R2;i++) // accessing the right column { A[i][C2]=B[x++]; } for(int i =C2-1;i>=C1;i--) // accessing the bottom row { A[R2][i]=B[x++]; } for(int i =R2-1;i>=R1+1;i--) // accessing the left column { A[i][C1]=B[x++]; } } void printArray() //Function for printing the array A[][] { for(int i=0;i

See:How to access Boundary Elements.

How to fill in a spiral format.

Output:Enter the size of the square matrix : 4 Enter the elements of the Matrix : Enter a value : 9 Enter a value : 2 Enter a value : 1 Enter a value : 5 Enter a value : 8 Enter a value : 13 Enter a value : 8 Enter a value : 4 Enter a value : 15 Enter a value : 6 Enter a value : 3 Enter a value : 11 Enter a value : 7 Enter a value : 12 Enter a value : 23 Enter a value : 8 ********************* The original matrix: ********************* 9 2 1 5 8 13 8 4 15 6 3 11 7 12 23 8 ********************* The Rearranged matrix: ********************* 23 15 12 11 1 13 8 9 2 6 3 8 4 5 7 8 ********************* The sum of boundary elements is = 105