I have been trying to print different patterns using for loop statement in java. And now I want to learn how to print the following pattern. It is basically an inclined pyramid type of pattern.
*
**
***
****
***
**
*
I tried to make it and I did get the right results but the problem is that I think that the way I did it is an inconvenient way of doing it. Here is the code:
for (int x = 1; x <= 4; x++) {
for (int y = 1; y <= x; y++) {
System.out.print("*");
}
System.out.println();
}
for (int x = 1; x <= 3; x++) {
for (int y = 3; y >= x; y--) {
System.out.print("*");
}
System.out.println();
}
解决方案
Your code produces the right output and it clear enough to me. The only suggestion I could make is to use a variable for the size of the pyramid instead of a hard-coded value.
You could write it in a more compact manner, only using 2 loops, like this:
int size = 7;
for (int row = 0; row < size; row++) {
for (int column = 0; column <= Math.min(size-1-row, row); column++) {
System.out.print("*");
}
System.out.println();
}
The idea here is that:
For each row of the pyramid (so the row goes from 0 to size excluded)
We need to determine how many asterisks to print. If we are in the upper-half of the pyramid, it is the equal to the row we're at. It we are in the lower-half of the pyramid, it is equal to size-1-row (decreasing with the row increasing). So the count of asterisk is the minimum of row and size-1-row: this is factored in a single statement using Math.min(size-1-row, row).