Nested Loops
As you have seen in some of the preceding examples, one loop can be nested inside of another. Nested loops are used to solve a wide variety of programming problems and are an essential part of programming. So, before leaving the topic of Java’s loop statements, let’s look at one more nested loop example. The following program uses a nested for loop to find the factors of the numbers from 2 to 100:
In the program, the outer loop runs i from 2 through 100. The inner loop successively tests all numbers from 2 up to i, printing those that evenly divide i. Extra challenge: The preceding program can be made more efficient. Can you see how? ...
Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.