How to Create Spiral Number Pattern Program in Java !!! with only one For Loop

14:22

Their are so many number pattern programs in programming language. Such as: 



All the number patterns shown above are common in programming field but
, there are so many number patterns which are not so common to made. one of those not so common number patterns.

I'm talking about the number pattern program for spiral matrix, that's look like a spiral.

Output of Spiral Matrix


The code i wrote is in java programming language but, you can easily alter that code in any other programming language by changing some printing statements, and the below written code of spiral matrix number pattern is using only one 'for' loop for making this spiral matrix of 2D array.

Spiral Matrix number pattern program code is written below :-

public class MatrixSpiral
{
 
  public static void main(String[] args)
  {
    int n = 5;
    int ar[][] = new int[n][n];
    int direction = 0;
    int rUp = n-1;
    int bUp = n-1;
    int lUp = 0;
    int uUp = 1;
    int x = 0,y=0;
    for(int i=1;i<=(n*n);i++) {
      if(direction == 0) {
       ar[x][y] = i;
        if(y==rUp) {
          rUp--;
          direction=1;
          x++;
        }else{
           y++;
        }
        
      }else if(direction == 1) {
       ar[x][y] = i;
        if(x==bUp) {
          bUp--;
          direction=2;
          y--;
        }else{
           x++;
        }

      }else if(direction == 2) {
        
       ar[x][y] = i;
        if(y==lUp) {
          lUp++;
          direction=3;
          x--;
        }else{
           y--;
        }

      }else if(direction == 3) {
       ar[x][y] = i;
        if(x==uUp) {
          uUp++;
          direction=0;
          y++;
        }else{
           x--;
        }
      }
    }
  for(int i=0;i<n;i++) {
      for(int j=0;j<n;j++) {
        if(ar[i][j] < 10) 
         System.out.print("0"+ar[i][j]+" ");
        else
          System.out.print(ar[i][j]+" ");
      }
      System.out.println();
    }
    
  }
}

    
if you have questions regarding this code you can comments down below:-

You Might Also Like

0 comments

If you have any questions or suggestions, you are free to ask, i will appreciate that and, i will try my best...

Google Ads