Computer Science

A square matrix is the matrix in which number of rows equals the number of columns. Thus, a matrix of order n*n is called a Square Matrix.

Write a program in Java to create a double dimensional array of size nxn matrix form and fill the cells of matrix in a circular fashion (clock wise) with natural numbers from 1 to n2, taking n as an input. Input n should be an odd number and filling of the elements should start from the central cell.

For example, if n = 5, then n2 = 25, then the array is filled as:

2122232425
2078910
1961211
1854312
1716151413

Java

Java Arrays

11 Likes

Answer

import java.util.Scanner;

public class KboatMatrixClockwise
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the size of the matrix: ");
        int n = in.nextInt();

        if (n % 2 == 0) {
            System.out.println("Invalid Input! Size must be an odd number");
            return;
        }
        
        int val  = 1;
        int arr[][] = new int[n][n]; 

        int x = n / 2;
        int y = n / 2;
        int d = 0;
        int c = 0;
        int s = 1;
        
        for (int k = 1; k <= (n - 1); k++) {
            for (int j = 0; j < (k < n - 1 ? 2 : 3); j++) {
                for (int i = 0; i < s; i++) {
                    arr[x][y] = val++;
                    
                    switch (d) {
                        case 0:
                        y = y + 1;
                        break;
                        
                        case 1:
                        x = x + 1;
                        break;
                        
                        case 2:
                        y = y - 1;
                        break;
                        
                        case 3:
                        x = x - 1;
                        break;
                    }
                }
                
                d = (d + 1) % 4;
            }
            
            s = s + 1;
        }
        
        arr[0][n-1] = val;

        System.out.println("Circular Matrix Clockwise:");
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output

Answered By

2 Likes


Related Questions