How to print vertical numerical patterns in Java

This is a post where we deal with a few vertical numerical patterns using Java.

We store the created patterns in Java Arrays and then print them.
Finally the patterns are created directly without using arrays.

 

 

To, generate this pattern we will first generate the required indices. The indices to be accessed in serial order are.
(0,0) (1,0) (2,0) (3,0) (4,0) (5,0)
(1,1)(2,1) (3,1) (4,1) (5,1)
(2,2) (3,2) (4,2) (5,2)
(3,3) (4,3) (5,3)
(4,4) (5,4)
(5,5)

Study it carefully. Let us have y for the rows and x for the columns and n is the number of rows.Then we have.

n=5

  1. (y,x) x=0 and y= 0 to 5
  2. (y,x) x=1 and y= 1 to 5
  3. (y,x) x=2 and y= 2 to 5
  4. (y,x) x=3 and y= 3 to 5
  5. (y,x) x=4 and y= 4 to 5
  6. (y,x) x=5 and y= 5 to 5

This can be simplified into x= 0 to n and y=x to n

This leads us to this program.

int n=5;

for(int x=0;x<=n;x++)
{
for(int y=x;y<=n;y++)
{
System.out.print("(" + y + "," + x + ")" + "\t");

}
System.out.println();
}

 

The output is

 

Now, we need to traverse this path in the array and add an increasing sequence throughout. This is easily done.

 

int n=5;
int[][] a=new int[n][n];
int sequence=0;

//Create the array
for(int x=0;x<=n-1;x++)
{
for(int y=x;y<=n-1;y++)
{
sequence++;
a[y][x]=sequence;

}

}


//Print the array
for(int x=0;x<=n-1;x++)
{
for(int y=0;y<=n-1;y++)
{
if(a[x][y]!=0)
System.out.print("\t" + a[x][y]);
else
System.out.print("\t");
}
System.out.println();
}

 

 

if you want a horizontal pattern just reverse x and y.

 

int n=5;
int[][] a=new int[n][n];
int sequence=0;
for(int x=0;x<=n-1;x++)
{
for(int y=x;y<=n-1;y++)
{
sequence++;
a[x][y]=sequence;

}

}


//Print the array
for(int x=0;x<=n-1;x++)
{
for(int y=0;y<=n-1;y++)
{
if(a[x][y]!=0)
System.out.print("\t" + a[x][y]);
else
System.out.print("\t");
}
System.out.println();
}

 

 

If you want to do it without using an array you can solve it in this fashion

The pattern can be represented as
value=y, value=value + n-1 , value=value + n-2, value=value + n-3 ….

This leads us to the following program.

int n=6;

for(int y=1;y<=n;y++)
{
int increment=n-1;
int value=y;
System.out.print(value + "\t" );
for(int x=1;x<=y-1;x++)
{
value=value+ increment;
System.out.print(value + "\t");
increment--;

}
System.out.println();
}

Leave a Reply