Nested Loops in Java (With an Example)
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:
1 2 3 4 5 6 7 8 9 10 11 |
public class Test{ public static void main(String[] args){ for(int i=0; i<3; i++){ for(int j=0; j<5; j++){ System.out.print("* "); } System.out.println(); } } } |
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:
1 2 3 |
for(int j=0; j<5; j++){ System.out.print("* "); } |
Then we have to display this row 3 times, meaning we have to nest the second "for" loop inside the first "for" loop:
1 2 3 4 5 6 |
for(int i=0; i<3; i++){ for(int j=0; j<5; j++){ System.out.print("* "); } System.out.println(); } |
Mission accomplished 🙂
You can find more articles in our Java Tutorial for Beginners.