Spiral matrix in java – Java Program to Print the elements of the Matrix in Spiral Form

Spiral matrix in java: In the previous article, we have seen Java Program to Print Matrix in Z form

In this article we are going to see how we can write a program to how to print Matrix in spiral from.

Java Program to Print the elements of the Matrix in Spiral Form

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element.
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to print Matrix in spiral from.

Method: Java Program to Print the elements of the Matrix in Spiral Form By Static Initialization of Array Elements

Approach:

  • Initialize and declare a matrix.
  • Traverse the matrix through [0,0] point and traverse by row wise.
  • Take 1st for loop to move from left to right.
  • Take 2nd for loop to move top to bottom.
  • Take 3rd for loop to move right to left.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
      int mat[][]={{10,20,30},{40,50,60},{70,80,90}};
      int a = 0;
      int b = mat.length-1;
      int c = 0;
      int d = mat[0].length-1;
      while(a <= b && c <= d)
      {
         for (int x = a; x <= d; x++) 
         {
            System.out.print(mat[a][x] + " ");
         }
         for (int x = a+1; x <= b; x++)
         {
            System.out.print(mat[x][d] + " ");
         }
         if(a+1 <= b)
         {
            for (int x = d-1; x >= c; x--) 
            {
               System.out.print(mat[b][x] + " ");
            }
         }
         if(c+1 <= d)
         {
            for (int x = b-1; x > a; x--) 
            {
               System.out.print(mat[x][c] + " ");
            }
         }
         a++;
         b--;
         c++;
         d--;
      }
   }
}
Output:

10 20 30 60 90 80 70 40 50

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Related Java Programs: