Search⌘ K

Nested Loops

Explore how nested loops operate in Java by creating a square pattern of stars. Understand the logic behind loops within loops, controlling iterations, and applying these concepts to solve problems involving repeated actions. This lesson helps you grasp fundamental looping techniques essential for Java programming.

Problem statement

Imagine that we want to display a square pattern of stars (asterisks), such as:

* * * *
* * * *
* * * *
* * * *

where the number of rows and the number of stars per row are the same. This number is essentially the length of the side of the square. However, we might not know this length in advance. If we ask the user for this value—call it n—we need a loop to display n stars in one row. We need ...