I am trying to write a code that repeats a "star" in the form of a pyramid and my code works fine but it is not a pyramid that starts from the middle with one star but starts from the right, how can I make it start from the middle?
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
System.out.println();
}
The output is not what I want.
I thought about trying to change the i in the second episode but I didn’t know how to change it to give me the correct result
>Solution :
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= (2 * i) - 1; k++) {
System.out.print("*");
}
System.out.println();
}
Here slightly modification to yours existing code. In second inner loop for k, where k<=i replace with k<=(2*i)-1,This ensure the number of stars in each row increases by two for each subsequent row.