Wednesday , 22 May 2019
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++) { A[r1][i]=k--; } for(int j=r1+1;j<=r2;j++) { A[j][c2]=k--; } 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


java spiral circular output

Check Also

Infix Postfix Prefix Conversion – Correct Method (ISC Computer Science)

In this video we discuss about the correct way of converting an Infix Expression to Postfix and Prefix.


  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

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