SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Sorting Non-Boundary Matrix Elements Program in Java and Python

17 February 2016

ISC 2016 Question 2 solution to sort the non-boundary elements of a square matrix, display diagonal elements and find their sum.

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:

  1. Sort the non-boundary elements in ascending order using any standard sorting technique and rearrange them in the matrix.
  2. Calculate the sum of both the diagonals.
  3. Display the original matrix, rearranged matrix and only the diagonal elements of the rearranged matrix with their sum.

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 9 2 1 5 8 3 6 4 15 8 13 11 7 12 23 8 DIAGONAL ELEMENTS 9 5 3 6 8 13 7 8 SUM OF THE DIAGONAL ELEMENTS = 59

Algorithm:

Step 1: Start.

Step 2: Create a Scanner object to accept input.

Step 3: Accept the order of the square matrix in m.

Step 4: If m < 4 or m > 9, display Invalid Range and go to Step 17.

Step 5: Declare a two-dimensional array A of size m x m.

Step 6: Calculate the number of non-boundary elements as n = (m - 2) * (m - 2).

Step 7: Declare a one-dimensional array B of size n.

Step 8: Use nested loops to input all elements of A row by row.

Step 9: Display the original matrix.

Step 10: Traverse A and copy every element whose row and column are not on the boundary into B.

Step 11: Sort B in ascending order using nested loops and swapping.

Step 12: Traverse the non-boundary positions of A again and place the sorted values from B back into those positions.

Step 13: Display the rearranged matrix.

Step 14: Set sum = 0 for the diagonal sum.

Step 15: Traverse the matrix and print an element only when i == j or i + j == m - 1; otherwise print a blank space.

Step 16: Add every printed diagonal element to sum and display the final sum.

Step 17: Stop.

Explanation:

The matrix has two kinds of positions: boundary positions and non-boundary positions. Boundary positions are found in the first row, last row, first column and last column. These values must remain fixed in this problem. Only the inner part of the matrix, which excludes the boundary, is sorted. Since the order of the matrix must be greater than 3 and less than 10, the valid values of M are 4 to 9. If the entered size is outside this range, the program displays an error message and stops further matrix processing.

The program first inputs the full matrix into the two-dimensional array A. To sort only the non-boundary part conveniently, it copies the inner elements into the one-dimensional array B. A position is non-boundary only when its row index is not 0, its column index is not 0, its row index is not m - 1 and its column index is not m - 1. For a matrix of order m, the inner portion has (m - 2) * (m - 2) elements, so that is the required size of B.

After storing the non-boundary values in B, the program sorts this one-dimensional array in ascending order. The original code uses a simple comparison and swap technique with two loops. Once sorted, the values from B are copied back into the non-boundary positions of A in row-major order. The boundary elements are never copied into B, and they are never overwritten while copying sorted values back. This keeps the outer border unchanged while rearranging only the inner values.

Finally, the program displays the diagonal elements of the rearranged matrix. The primary diagonal contains positions where the row and column indexes are equal, that is i == j. The secondary diagonal contains positions where i + j == m - 1. Whenever either condition is true, the element is printed and added to the sum. Other positions are printed as blank tab spaces so that the diagonal shape remains visible on the screen.

Java Program:

Java
/**
* The class SortNonBoundary_ISC2016 inputs a square matrix,
* sorts the non-boundary elements in ascending order and
* displays the diagonal elements with their sum.
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC Practical 2016 Question 2
*/

import java.util.Scanner;

class SortNonBoundary_ISC2016
{
    int A[][];
    int B[];
    int m;
    int n;

    boolean input()
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the size of the square matrix : ");
        m = sc.nextInt();

        if(m < 4 || m > 9)
        {
            System.out.println("Invalid Range");
            return false;
        }

        A = new int[m][m];
        n = (m - 2) * (m - 2);
        B = new int[n]; // Array to store non-boundary elements.

        System.out.println("Enter the elements of the Matrix : ");
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < m; j++)
            {
                System.out.print("Enter a value : ");
                A[i][j] = sc.nextInt();
            }
        }

        return true;
    }

    /*
    * If s is 1, copy non-boundary elements from A[][] to B[].
    * Otherwise, copy sorted elements from B[] back to A[][].
    */
    void convert(int s)
    {
        int x = 0;

        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < m; j++)
            {
                if(i != 0 && j != 0 && i != m - 1 && j != m - 1)
                {
                    if(s == 1)
                        B[x] = A[i][j];
                    else
                        A[i][j] = B[x];

                    x++;
                }
            }
        }
    }

    void sortArray()
    {
        int c;

        // Sort the non-boundary elements stored in B[].
        for(int i = 0; i < n - 1; i++)
        {
            for(int j = i + 1; j < n; j++)
            {
                if(B[i] > B[j])
                {
                    c = B[i];
                    B[i] = B[j];
                    B[j] = c;
                }
            }
        }
    }

    void printArray()
    {
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < m; j++)
            {
                System.out.print(A[i][j] + "\t");
            }
            System.out.println();
        }
    }

    void printDiagonal()
    {
        int sum = 0;

        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < m; j++)
            {
                if(i == j || (i + j) == m - 1)
                {
                    System.out.print(A[i][j] + "\t");
                    sum = sum + A[i][j];
                }
                else
                {
                    System.out.print("\t");
                }
            }
            System.out.println();
        }

        System.out.println("Sum of the Diagonal Elements : " + sum);
    }

    public static void main(String args[])
    {
        SortNonBoundary_ISC2016 ob = new SortNonBoundary_ISC2016();

        if(ob.input())
        {
            System.out.println("*********************");
            System.out.println("The original matrix:");
            System.out.println("*********************");
            ob.printArray();

            ob.convert(1);  // Store non-boundary elements in B[].
            ob.sortArray(); // Sort the non-boundary elements.
            ob.convert(2);  // Put sorted values back into A[][].

            System.out.println("*********************");
            System.out.println("The Rearranged matrix:");
            System.out.println("*********************");
            ob.printArray();

            System.out.println("*********************");
            System.out.println("The Diagonal Elements:");
            System.out.println("*********************");
            ob.printDiagonal();
        }
    }
}

Equivalent Python Program:

Python
# Program to sort the non-boundary elements of a square matrix
# and display the diagonal elements with their sum.

m = int(input("Enter the size of the square matrix : "))

if m < 4 or m > 9:
    print("Invalid Range")
else:
    matrix = []
    non_boundary = []

    print("Enter the elements of the Matrix : ")

    # Input the matrix elements row by row.
    for i in range(m):
        row = []
        for j in range(m):
            value = int(input("Enter a value : "))
            row.append(value)
        matrix.append(row)

    print("*********************")
    print("The original matrix:")
    print("*********************")
    for i in range(m):
        for j in range(m):
            print(matrix[i][j], end="\t")
        print()

    # Store only the non-boundary elements.
    for i in range(m):
        for j in range(m):
            if i != 0 and j != 0 and i != m - 1 and j != m - 1:
                non_boundary.append(matrix[i][j])

    # Sort the non-boundary elements.
    non_boundary.sort()

    # Put the sorted values back into the non-boundary positions.
    index = 0
    for i in range(m):
        for j in range(m):
            if i != 0 and j != 0 and i != m - 1 and j != m - 1:
                matrix[i][j] = non_boundary[index]
                index += 1

    print("*********************")
    print("The Rearranged matrix:")
    print("*********************")
    for i in range(m):
        for j in range(m):
            print(matrix[i][j], end="\t")
        print()

    print("*********************")
    print("The Diagonal Elements:")
    print("*********************")

    diagonal_sum = 0
    for i in range(m):
        for j in range(m):
            if i == j or i + j == m - 1:
                print(matrix[i][j], end="\t")
                diagonal_sum += matrix[i][j]
            else:
                print(end="\t")
        print()

    print("Sum of the Diagonal Elements :", diagonal_sum)

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: ********************* 9 2 1 5 8 3 6 4 15 8 13 11 7 12 23 8 ********************* The Diagonal Elements: ********************* 9 5 3 6 8 13 7 8 Sum of the Diagonal Elements : 59

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →