This code is an example of how to create a Christmas tree pattern using asterisks (*
) and vertical bars (|
).
public class PatternChristmasTree {
public static void main(String[] args) {
int n = 10, i, j, k;
for (i = 0; i < n; i++) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print("*");
for (k = 0; k <= i-1; k++) {
System.out.print("|");
}
for (j = 1; j < i; j++) {
System.out.print("|");
}
if (i > 0) {
System.out.print("*");
}
System.out.println();
}
}
}
The result of running this program is a pattern that looks like a Christmas tree made up of stars and vertical bars.
*|*
*|||*
*|||||*
*|||||||*
*|||||||||*
*|||||||||||*
*|||||||||||||*
*|||||||||||||||*
*|||||||||||||||||*
public class PatternChristmasTree
.public static void main(String[] args)
.n
is declared and initialized to 10
. This variable determines the height of the tree.i
, j
, and k
are declared.for
loop is used to iterate from 0 to n-1
(inclusive) using the variable i
. This loop prints each row of the tree.for
loop is used to print spaces before the star symbol. The loop uses the variable j
to print n-i
spaces.System.out.print("*")
.for
loop is used to print |
characters on the left side of the tree. The loop uses the variable k
to print i-1
|
characters.for
loop is used to print |
characters on the right side of the tree. The loop uses the variable j
to print i-1
|
characters.|
characters, a star symbol is printed on the right side of the tree if the current row is not the top row. This is checked using an if
statement that tests if i > 0
.System.out.println()
to move to the next row of the tree.for
loop ends, the main method ends and the program terminates.