Home / Blue J / Bluej/Java program for spiral matrix

Bluej/Java program for spiral matrix

This is a java program for spiral matrix.

Spiral matrix
Outer spiral matrix– arrows are from boundary to core element. Inner Spiral matrix– Arrows are from core elements to boundary elements.
import java.util.*;     //for importing scanner class 
class spiral
{
	public static void main(String args[])
	{
	Scanner obj=new Scanner(System.in);   //can also be done by BufferReader. But then use: import.java.io.*;
	System.out.print("\nEnter the size of matrix (nxn):");
	int n=obj.nextInt();
	int a[][]=new int[n][n];
	System.out.println("Your matrix is of order "+n+"x"+n+"\n");
	int d,c,i,j,l,t,m,k;
	d=n-1;
	c=n*n+1;     // if its 3x3 matrix then 1-9 elements are filled. So c=10. afterwards --c making 9,8,.....1
	for(i=0;i<=(n+1)/2;i++)
	{
		for(j=i;j<=d;j++)   //first from west to east
			a[i][j]=--c;
			for(l=i+1;l<=d;l++)   //    north to south
			a[l][d]=--c;

			for(k=d-1;k>=i;k--)      //east to west
			a[d][k]=--c;

			for(m=d-1;m>i;m--)   //south to north
			a[m][i]=--c;

			d--;               // reducing the size of spiral
		}

	for(i=0;i<n;i++)
	{
		for(j=0;j<n;j++)
		System.out.print(a[i][j]+"\t");
	System.out.println();
	}
}
}

OUTPUT:

Java program for spiral matrix
Java program for spiral matrix

Tags: Bluej program for spiral matrix, java program for spiral matrix.

Also See:   Harshad Number Program in Java (Niven Numbers)

Check Also

Program for Fascinating Number in JAVA

Fascinating Number :- The number of 3 digit or more, when we multiplied that number ...

2 comments

  1. tri mueri sandes

    hello, i need your help, can you make a java program sentence matrix spiral? thank you, send or tag me trimuerisandes@gmail.com my pin bb 321e5cd9

  2. Outside to inside spiral with inc. Values pls…..

Leave a Reply

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