Lesson 4

Navigating the Cosmos of Java: Understanding Nested Loops

Introduction

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!

Nested Loops: The Basics

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).

Java
1for (initialization; condition; iteration) { 2 // outer loop code 3 for (initialization; condition; iteration) { 4 // inner loop code 5 } 6}

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.

Java Nested 'for' Loops

Writing nested for loops in Java is simple. To demonstrate, let's print a 5x5 star pattern using nested loops:

Java
1for (int i = 0; i < 5; i++) { 2 for (int j = 0; j <= i; j++) { 3 System.out.print("* "); // print "* " 4 } 5 System.out.println(); // move to the next line 6} 7// Prints: 8// * 9// * * 10// * * * 11// * * * * 12// * * * * *

Here, the outer loop governs the rows, while the inner one controls columns. The result: a diagonal pattern of stars printed on the console!

Java Nested 'while' Loops

Nested while loops function similarly to nested for loops. The following example prints five sequences, each descending from 5 to 1:

Java
1int i = 5; 2while (i > 0) { 3 int j = i; 4 while (j > 0) { 5 System.out.print(j + " "); // print number 6 j--; // decrement the value of j 7 } 8 System.out.println(); // move to the next line 9 i--; // decrement the value of i 10} 11// Prints: 12// 5 4 3 2 1 13// 4 3 2 1 14// 3 2 1 15// 2 1 16// 1

Upon executing this, you'll see five lines, containing decreasing numbers, as shown in the comment.

Advanced Tasks with Nested Loops

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:

Java
1int[][] intArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 2 3for (int i = 0; i < intArray.length; i++) { // iterates over rows 4 for (int j = 0; j < intArray[i].length; j++) { // iterates over columns 5 System.out.print(intArray[i][j] + " "); // prints each element 6 } 7 System.out.println(); // moves to the next line 8} 9// Prints: 10// 1 2 3 11// 4 5 6 12// 7 8 9

To search for a number in a 2D array, nested loops work superbly. Here's a demonstration that searches for the number 7:

Java
1int[][] intArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 2int searchNumber = 7; 3boolean isFound = false; 4 5for (int i = 0; i < intArray.length; i++) { // iterates over rows 6 for (int j = 0; j < intArray[i].length; j++) { // iterates over columns 7 if (intArray[i][j] == searchNumber) { 8 System.out.println("Number " + searchNumber + " found at [" + i + ", " + j + "]"); 9 isFound = true; 10 } 11 } 12} 13 14if (!isFound) { 15 System.out.println("Number " + searchNumber + " not found in the array."); 16} 17// Prints: Number 7 found at [2, 0]

When we run the code, our nested loops find the number 7 in the third row.

Quick Nested Loops Tips and Warnings

Though nested loops are extraordinarily powerful, be sure to avoid common pitfalls such as infinite loops (ensure your loop will eventually exit). Remember, the proper controls and conditional statements are significant.

Lesson Summary and Practice

Congratulations! You now understand the concept of nested loops and can effectively use for and while loops in Java. Shortly, you'll work on practice exercises to apply your newfound knowledge and enhance your understanding of loops in Java. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.