[Solved] Logic behind printing pyramid shape using nested for loops in Java


Nested for loops like that are used when you have pseudo code like this:

Do the following x times:
    Do the following y times:
        some stuff
    Do the following z times:
        some stuff

In your specific case, the size of the pyramid is dynamic and is stored in a variable called size. To print a pyramid, you have to print size times the following thing:

  • Some whitespace and some *

How do you print that then? You calculate how many white spaces and * should there be and print them. Since the numbers of whitespaces and * are dynamic, you need a for loop to do this, instead of hardcoding them in.

Do you see the structure now?

The outer loop prints each layer of the pyramid. The first inner loop prints the white spaces and the second inner loop prints the *.

solved Logic behind printing pyramid shape using nested for loops in Java