For Loops Pyramid

Ray Alva
3 min readApr 26, 2021
Photo by Michael Dziedzic on Unsplash

Lately I decided to learn a new programming language. I decided to go with Java because there is so many resources and it is relatively easy to learn. One of the first problems I solved using Java was to print a pyramid shape using for loops. It was a fun little problem so I would love to share my thought process.

This is what the pyramid shape is supposed to look like.

    *
***
*****
*******
---------

I broke this down into multiple for loops. First I needed a for loop that would print a whole layer of the pyramid one by one. So let’s keep it simple and start with that.

int num = 4;for (int i = 1; i <= num; i++) {
System.out.println("");
}

The num variable represents the number of layers that the pyramid will have. In the for loop we are printing a new line after each layer is created. Now we take another look at our pyramid and see that every layer starts with spaces first. The spaces are decremented after each layer. Also notice that num is equal to the number of spaces the pyramid starts with. We can use another loop to first print the spaces. It should look like this.

int num = 4;for (int i = 1; i <= num; i++) {  for (int j = i; j <= num; j++) {
System.out.print(" ");
}
System.out.println("");
}

Very simple right? In this new for loop we set the variable j equal to our variable i from the outer for loop. This is so that the correct number of spaces prints out after every layer is done. Next we need to actually print out the stars that will represent the body of the pyramid. Another simple for loop will do the trick. This for loop will start once the spaces for loop is done. It will look like this.

int num = 4;for (int i = 1; i <= num; i++) {  for (int j = i; j <= num; j++) {
System.out.print(" ");
}
for (int k = 1; k < (i * 2); k++) {
System.out.print("*");
}
System.out.println("");
}
System.out.println("-----------");

Awesome! This new loop prints a star for every iteration. The difference here is that in the condition we check to see if k is less than i times 2. This is because each layer increments the number of stars being printed by 2. Notice we also added a line at the end that prints out the base of the pyramid once the body is done printing.

Nice pyramid! This is such a simple problem that helps you get used to using loops in different ways. There are other shapes you can try to print using loops in Java. For an extra challenge try inverting the pyramid. Have fun and happy coding. 😎

--

--

Ray Alva

Software engineer with a passion for building applications. I love nature, gaming, cooking and of course coding!