Note that your code prints *
characters, but should print #
characters, and that there should be single spaces between the #
characters.
Wrong Correct
* #
*** # # #
***** # # # # #
******* # # # # # # #
So, for the fun of it, here is an non-traditional way to do it the correct way for any size tree:
private static void printChristmasTree(int n) {
final int w = n * 2 - 1;
char[] buf = new char[w * 3 - 2];
Arrays.fill(buf, ' ');
for (int i = w - 1; i < buf.length; i += 2)
buf[i] = '#';
for (int s = 0; s < w; s += 2)
System.out.println(new String(buf, s, s + w));
}
Output from printChristmasTree(6)
:
#
# # #
# # # # #
# # # # # # #
# # # # # # # # #
# # # # # # # # # # #
Anyway, back to your code. Your output for n = 6
is:
*
***
*****
Your outer for
loop uses i=i+2
1, which means you only get half the number of rows you need. Either change to i++
, or change condition to i < n * 2
. Let's go with second option, even though that would only make sense if you intended to print spaces between stars.
1) Better written as i += 2
That changes output to:
*
***
*****
*******
*********
***********
Now the number of rows is correct, and the number of stars on each row is correct. Let's look at your space indenting loop.
Since j = n/2 = 3
, the condition j==0
is immediately false, and that is why you don't get any spaces.
Perhaps you meant j != 0
, but the problem is that the loop doesn't use the i
value, so that would always print 3 spaces. We can fix that by starting the loop with j = n - i / 2 - 1
.
Fixed code:
private static void printChristmasTree(int n) {
for (int i = 0; i < n * 2; i += 2) {
for (int j = n - i / 2 - 1; j > 0; j--)
System.out.print(" ");
for (int k = 0; k <= i; k++)
System.out.print("*");
System.out.println();
}
}
Output:
*
***
*****
*******
*********
***********
If we had chosen the first option earlier, i.e. change to i++
, the code would be (with some other slight changes):
private static void printChristmasTree(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--)
System.out.print(' ');
for (int j = i * 2; j >= 0; j--)
System.out.print('*');
System.out.println();
}
}