Monday , 27 February 2017
Home » Array Related Programs » Java program to print a variation of Circular (Spiral) Matrix

Java program to print a variation of Circular (Spiral) Matrix


Write a Program in Java to fill a square matrix of size ‘n*n” in a spiral fashion (from the inside) with natural numbers from 1 to n*n, taking ‘n’ as input.

For example: if n = 5, then n*n = 25, hence the array will be filled as given below.

circular spiral matrix-1

Note: Don’t be confused as to how the filling will start from the center. Just treat the above program as (see the difference in the direction of the arrows):

circular spiral matrix-2


So, you see, this question is nothing but the same circular matrix which we did earlier (See: Java Program to print Circular (Spiral) Matrix). The only change is that here the filling of numbers is from ‘n*n’ to 1 every time decreasing by one. In the earlier program it was from 1 to ‘n*n’ every time increasing by one.

So slight changes in our earlier program will result into this new spiral matrix. The changes will be:

  • Start ‘k’ from ‘n*n’ and not 1
  • Change the condition in while loop to while(k >= 1)
  • Decrease the value of ‘k’ every time as ‘k- -‘


* The class Circular_Matrix2 creates a Square Matrix of size n*n and fills it in a circular fashion
* @author :
* @Program Type : BlueJ Program - Java

class Circular_Matrix2
        public static void main(String args[])throws IOException
            BufferedReader br=new BufferedReader(new InputStreamReader(;
            System.out.print("Enter the number of elements : ");
            int n=Integer.parseInt(br.readLine());

            int A[][]=new int[n][n];
            int k=n*n, c1=0, c2=n-1, r1=0, r2=n-1;

                    for(int i=c1;i<=c2;i++)

                    for(int j=r1+1;j<=r2;j++)

                    for(int i=c2-1;i>=c1;i--)

                    for(int j=r2-1;j>=r1+1;j--)

            /* Printing the Circular matrix */
            System.out.println("The Circular Matrix is:");
            for(int i=0;i<n;i++)
                    for(int j=0;j<n;j++)
                            System.out.print(A[i][j]+ "\t");


java spiral circular output

Check Also

[Question 2] ISC 2017 Computer Practical Paper Solved – Quiz Result

Solution of Program 2 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input the answers of each participant row-wise and calculate their marks


  1. Can I write programs in the practical examinations without using ‘static void main’?
    Is it permissible to write programs that create objects graphically in BlueJ.

Leave a Reply to Java For School Cancel reply

Your email address will not be published. Required fields are marked *