Circular matrix

Circular matrix: Write a Program in Java to fill a square matrix of size ā€˜n*nā€ in a circular fashion (clockwise) with natural numbers from 1 to n*n, taking ā€˜nā€™ as input.
For example: if n = 4, then n*n = 16, hence the array will be filled as given below.
Input : m = 4, n = 4
Output : 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

To learn more about how to take input using Buffered Reader in java watch the given video.
https://youtu.be/bTOMwnwpXqs
import java.io.*;
class Circular
{
public static void main()throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the length of the double dimensions-rows&columns-- ONLY ONE DIGIT IS TO BE ENTERED FOR BOTH");
    int r=Integer.parseInt(br.readLine());
    int c=r;
    int Arr[][]=new int[r][c];
    int k=1;
    int c1=0;
    int c2=c-1;
    int r1=0;
    int r2=r-1;
    System.out.println("--------CIRCULAR MATRIX------------");
    while(k<=(r*c))
    {
        for(int i=c1;i<=c2;i++)
        {
            Arr[r1][i]=k++;
        }
        for(int j=r1+1;j<=r2;j++)
        {
            Arr[j][c2]=k++;
        }
        for(int i=c2-1;i>=c1;i--)
        {
            Arr[r2][i]=k++;
        }
        for(int i=r2-1;i>=r1+1;i--)
        {
            Arr[i][c1]=k++;
        }
        c1 ++;
        c2 --;
        r1 ++;
        r2 --;
    }
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            System.out.print(Arr[i][j]+"\t");
        }
        System.out.println();
    }
}

Input: Enter the length of the double dimensions-rows&columns– ONLY ONE DIGIT IS TO BE ENTERED FOR BOTH
4
Output:
——–CIRCULAR MATRIX————
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

To learn more matrix programs click
https://java4school.com/anticlockwise-circular-matrix

LEAVE A REPLY

Please enter your comment!
Please enter your name here