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 numbers in a circular fashion (anticlock-wise) with natural numbers from 1 to n2, taking n as an input. The filling of the elements should start from outer to the central cell.

For example, if n=4, then n2=16, then the array is filled as:

 
1 ↓
 
↓ 12

11

10
2 ↓↓ 1316 ↑9   ↑
3 ↓   14
   →
15 ↑
 
8   ↑
4
   5
6
7   ↑
 

Java

Java Arrays

11 Likes

Answer

import java.util.Scanner;

public class KboatMatrixCircularFill
{
    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();
        int x = 1;
        int arr[][] = new int[n][n];
        
        int a = 0;
        int b = n - 1;
        
        while (a < n) {
            
            for (int i = a; i <= b; i++) {
                arr[i][a] = x++;
            }
            
            a++;
            
            for (int i = a; i <= b; i++) {
                arr[b][i] = x++;
            }
            
            
            for (int i = b - 1; i >= a - 1; i--) {
                arr[i][b] = x++;
            }
            
            b--;
            
            for (int i = b; i >= a; i--) {
                arr[a-1][i] = x++;
            }
        }
        
        System.out.println("Circular Matrix Anti-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

5 Likes


Related Questions