java_number_patterm

In this program, we are going to print a hollow rectangular pattern in Java with only numbers. This program takes input from the user, so the output depends on the user input. If the input is 6, the output will be:

CODE

CODE EXPLANATION

First of all, we need three for loops for this program. One for the rows, one for the columns and another loop for the last row.

We have used BufferedReader to take input from the user.

Now let’s split the program into smaller parts to make it easier to understand.

Suppose the user input is 5. Which means n=5.
Now if you run the above code, you will get the output like this: 12345. Because you can see that we are printing the value of j only if i==1 or the row is 1.
Also, notice that the condition of the outer for loop is i<n and inner for loop is j<=n.

Here the output of the above code is:

When i==1, the output is: 12345.
After that, i is incremented by 1 and becomes 2 or i == 2.

So when i == 2, print the value of j only if j == 1 and j == 5 (here n == 5).
When j == 1, print (j+i-1).
Here j == 1 + i == 2 1. So it becomes 2 (1+2-1).

When j == 5, print (j-(i-1)).
Here (j == 5 ( i==2 1)). So it becomes 4 (5-(2-1)).

i is incremented by 1. Now we are at row 3 or i == 3. Again print the value of j only if j == 1 and
j == 5 (here n==5).

When j == 1, print (j+i-1).
Here j == 1 + i == 3  1. So it becomes 3 (1+3-1).

When j == 5, print (j-(i-1)).
Here (j == 5 ( i==3  1)). So it becomes 3 (5-(3-1)).

Again i is incremented by 1. Now the row becomes 4 or i == 4. Again print the value of j only if j == 1 and j == 5 (here n==5).

When j == 1, print (j+i-1).
Here j == 1 + i == 4  1. So it becomes 4 (1+4-1).

When j == 5, print (j-(i-1)).
Here (j == 5 ( i == 4  1)). So it becomes 2 (5-(4-1)).

To make it look like a rectangle, we are printing blank spaces when j!=1 and j!=5. Which means print numbers when j==1 and j==5, if not, print blank space.

The only thing is left is the last row. So now you can understand why we have taken the outer loop condition as i<n.
Anyway, to get the last row, we just need another for loop. 

And that is all, it will give us the expected output. I hope you all have understood the logic behind this program. Still, if you have any doubt, you can always let us know in the comment section. You can also comment a better solution of this program.

Number hollow star pattern – Java program
Tagged on:     

Leave a Reply

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