I want to print the below pattern
*
***************
* * * *
* * * *
* *
* * * *
* * * *
***************
*
I am able to print the two outer pyramids in the pattern using the below code:
public static void main(String[] args) {
int n = 8;
int i, j;
for (i = 1; i <= n; i++) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (i == n || j == 1 || j == (2 * i - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
for (i = n; i >= 1; i--) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (i == n || j == 1 || j == (2 * i - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
}
This prints the pattern as
*
* *
* *
* *
* *
* *
* *
***************
***************
* *
* *
* *
* *
* *
* *
*``
But how to combine these two to form a star shape?
Since you didn't specify what your restrictions were...
public static void main(String[] args) {
System.out.println(" * ");
System.out.println("***************");
System.out.println(" * * * * ");
System.out.println(" * * * * ");
System.out.println(" * * ");
System.out.println(" * * * * ");
System.out.println(" * * * * ");
System.out.println("***************");
System.out.println(" * ");
}
Now obviously that is not what you intend to do, but next time it would be of help if you are more specific about your requirements, i.e.: "I have to do it using only for loops", "I'm not allowed to print more than a character at a time", "the code must be able to print any star of a given width", etc.
Because if none of those restrictions are in place, then the best way is just to print the ASCII lines like above.
You could temporarily store the printing in a 2D char array and modify it twice, then use a for loop to print the array.
public static void main(String[] args) {
int n = 8;
char[][] temp = new char[][];
Arrays.fill(temp, ' ');
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= (2 * i - 1); j++) {
if (i == n || j == 1 || j == (2 * i - 1)) {
temp[i][j] = '*';
}
}
}
for (i = n; i >= 1; i--) {
for (j = 1; j <= (2 * i - 1); j++) {
if (i == n || j == 1 || j == (2 * i - 1)) {
temp[i][j] = '*';
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
System.out.print(temp[i][j]);
System.out.println();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With