Nested Loops in Java (With an Example)

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

This is one of the articles from our Java Tutorial for Beginners.


Task:

Write a program that will display asterisks in the console in the same pattern they're arranged here.

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

Solution:

If you run this code on your computer, you will see the following in the console:

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

Commentary:

The best approach is to divide this task into a few sub-tasks.

Step 1: Create a row of 5 asterisks with the help of the "for" loop.

Step 2: Display this row 3 times with the help of another "for" loop.

This means that we need nested loops.

The first step is to display the 5 asterisks in a row and we do that with the help of this code:

Then we have to display this row 3 times, meaning we have to nest the second "for" loop inside the first "for" loop:

Mission accomplished 🙂

You can find more articles in our Java Tutorial for Beginners. 

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--