Program opened below. You can scroll through the algorithm, Java code and output.

Boundary Primes and Diagonal Sum

Download .java

Question

Read a square matrix; display its prime boundary values in ascending order, and find the sum of both diagonals without counting the centre twice.

Step 1: Start and read square matrix order n. Step 2: Validate the order. Step 3: Create the matrix and a separate boundary-prime array. Step 4: Initialize the prime count and diagonal sum. Step 5: Read each element using nested loops. Step 6: Check whether the element lies on the top, bottom, left or right boundary. Step 7: For a boundary value, test primality by trial division. Step 8: Store the value in the prime array if it is prime. Step 9: Check whether the element lies on either diagonal. Step 10: Add diagonal values to the sum using a single OR condition. Step 11: This ensures the centre is counted only once. Step 12: Sort the collected boundary primes using insertion sort. Step 13: Print the sorted boundary values. Step 14: Print the diagonal sum. Step 15: Stop.
Java
import java.util.*;
class BoundaryPrime {
    static boolean prime(int n) {
        if (n < 2) {
            return false;
        }
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 1 || n > 20) {
            System.out.println("Invalid order");
            return;
        }
        int[][] a = new int[n][n];
        int[] primes = new int[n * n];
        int size = 0;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = sc.nextInt();
                if ((i == 0 || j == 0 || i == n - 1 || j == n - 1) && prime(a[i][j])) {
                    primes[size++] = a[i][j];
                }
                if (i == j || i + j == n - 1) {
                    sum += a[i][j];
                }
            }
        }
        for (int i = 1; i < size; i++) {
            int key = primes[i];
            int j = i - 1;
            while (j >= 0 && primes[j] > key) {
                primes[j + 1] = primes[j];
                j--;
            }
            primes[j + 1] = key;
        }
        for (int i = 0; i < size; i++) {
            System.out.print(primes[i] + " ");
        }
        System.out.println("Diagonal sum = " + sum);
    }
}
Input: 3 / 2 4 5 / 6 7 8 / 11 12 13 Output: 2 5 11 13 / Diagonal sum = 38
← Previous Program 22 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.