Java Program – Pattern 4

For n = 5
1*
2**
3***
4****
5*****
6****
7***
8**
9*
Program
1public class Pattern {
2 
3    public void print(int n) {
4        for (int i = 1; i <= n; i++) {
5            for (int j = 1; j <= i; j++) {
6                System.out.print("*");
7            }
8            System.out.println();
9        }
10        for (int i = n - 1; i >= 1; i--) {
11            for (int j = 1; j <= i; j++) {
12                System.out.print("*");
13            }
14            System.out.println();
15        }
16    }
17}
The given pattern can be split into two parts. The first part is :
1*
2**
3***
4****
5*****
And the second part is
1****
2***
3**
4*
The first part is the same as this pattern. The second part is same as this pattern with n replaced with n-1.

No comments:

Post a Comment