You are on page 1of 2

Ex No.

15
Date:
Spiral Matrix
Aim:
To write a java program to traverse a matrix in a spiral manner.
Source Code:
import java.io.*;
public class spiral
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter No of Elements: ");
int N = Integer.parseInt(in.readLine());
int[][] a = new int[N][N];
System.out.println("Enter the Elements: ");
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
a[i][j] = Integer.parseInt(in.readLine());
System.out.println("\n\n The spiral traverse is \n ");
for (int i = N-1, j = 0; i > 0; i--, j++)
{
for (int k = j; k < i; k++) System.out.print(" "+a[j][k]);
for (int k = j; k < i; k++) System.out.print(" "+a[k][i]);
for (int k = i; k > j; k--) System.out.print(" "+a[i][k]);
for (int k = i; k > j; k--) System.out.print(" "+a[k][j]);
}
if (N % 2 == 1) System.out.print(" "+a[(N-1)/2][(N-1)/2]);
}
}
Output:
Javac spiral,java
Java spiral
Enter No of Elements: 3
Enter the Elements: 1
2
3
4
5
6
7
8
9
The spiral traverse is
1 2 3 6 9 8 7 4 5
Result:
Thus a java program has been written to traverse a matrix spirally.