java-program-number-pattern-square-rectangle

This is my third post on pattern programs. In the last two posts, I have discussed how to draw square and rectangular star pattern.

1 – Java program to print star pattern (Rectangle / Square)

2 – Java program to print hollow start pattern (Rectangle / Square)

In this post, I am going to discuss how to draw square or rectangular pattern which contains only numbers, not stars.

About this program

This is a square pattern which contains numbers. and the pattern looks like this:

1  1  1  1  1
2  2  2  2  2
3  3  3  3  3
4  4  4  4  4
5  5  5  5  5

So the logic of this program is same as my previous posts but instead of stars,the first row contains only 1s, the second row contains only 2s, the third row contains only 3s and so on.

Code

 

Output

 

If  you want a square shaped pattern just add few spaces after “i“. See the below example:

 

Output

Code Explanation

Notice carefully that we are printing the value of “i“. That is because the first row should only contain 1s,  similarly the second row should only contain 2s and so on.

At first, 1 is assigned to the variable “i” (in the outer loop). Then the condition is checked. If the condition is true, the control flow enters into the inner loop.

 

 

Now that the control flow is inside the inner loop.  Now the body of the inner loop is executed for five times (The value of “i” is still 1). So basically we are printing the value of “i” five times.

So when the value of “i” is 1. It is  printed five times. Then the cursor goes to the next line and the incremented value of “i” is printed for five times. Again the cursor goes to the next line and the incremented value is printed. In this way, the execution continues.

3 – Java program to print number square pattern
Tagged on:         

Leave a Reply

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