I have to print pyrmids of stars by the user input, the user input: how many rows,and how many columns. i stared with 1 star and increment the stars every iteration by 2, and decrement the rows by 1. i cant to determine how many spaces i have to do.
what i have to do : examples :
printStars(4,2) rows = 4 , columns = 2.
output :
* *
*** ***
***** *****
******* *******
printStars(3,3) rows= 3 , columns =3.
output :
* * *
*** *** ***
***** ***** *****
printStars(3,4) rows = 3 , columns =4.
output:
* * * *
*** *** *** ***
***** ***** ***** *****
The code:
private static void printStars(int rows, int columns ) {
int stars = 1;
while (rows > 0) {
int spaces = rows;
for (int i = 1; i <= columns; i++) {
for (int sp = spaces; sp >=1; sp--) {
System.out.print(" ");
}
for (int st = stars; st >= 1; st--) {
System.out.print("*");
}
}
System.out.println();
stars += 2;
rows--;
}
}
what i get :
printStars(3,4)
output:
* * * *
*** *** *** ***
***** ***** ***** *****
At first sight it seems that you are not accounting for the spaces that come after you have printed the stars. Try to modify the code like this:
private static void printStars(int rows, int columns)
{
int stars = 1;
while (rows > 0) {
int spaces = rows;
for (int i = 1; i <= columns; i++) {
for (int sp = spaces; sp >= 1; sp--) {
System.out.print(" ");
}
for (int st = stars; st >= 1; st--) {
System.out.print("*");
}
for (int sp = spaces; sp >= 1; sp--) {
System.out.print(" ");
}
}
System.out.println();
stars += 2;
rows--;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments