Greetings! This lesson is key to mastering nested loops in Java. Just as your daily routine may involve multiple tasks (inner loops) you repeat for each day of the week (outer loop), a nested loop involves executing an inner loop within an outer loop. Let's start our journey!
Imagine each day involves multiple tasks like cooking and eating for each meal: breakfast, lunch, and dinner. Here, the meals represent the outer loop, and the tasks represent the inner loop. Similarly, in Java, we can write a for or while loop (inner loop) inside another for or while loop (outer loop).
Evaluate the condition of the outer loop. If it's true, enter the loop and complete the iterations of the inner loop before proceeding to the next iteration of the outer loop.
Writing nested for loops in Java is simple. To demonstrate, let's print a 5x5 star pattern using nested loops:
Here, the outer loop governs the rows, while the inner one controls columns. The result: a diagonal pattern of stars printed on the console!
Nested while loops function similarly to nested for loops. The following example prints five sequences, each descending from 5 to 1:
Upon executing this, you'll see five lines, containing decreasing numbers, as shown in the comment.
Nested loops are particularly useful for tasks such as traversing multi-dimensional arrays and performing complex searches.
Given a 2D array, let's print all elements using nested loops:
To search for a number in a 2D array, nested loops work superbly. Here's a demonstration that searches for the number 7:
When we run the code, our nested loops find the number 7 in the third row.
