Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want someone to tell me why I can't print the star in the shape of a pyramid?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading