6.11 Nested Loops

Loops can be nested inside other loops; that is, the body of one loop can contain another loop. For example, a while loop can be nested inside another while loop or a for loop can be nested inside another for loop. In fact, the nested loops do not need to be the same loop type; that is, a for loop can be nested inside a while loop, and a while loop can be nested inside a for loop.

Nested loops may be useful if we are performing multiple operations, each of which has its own count or sentinel value. Going back to Jane, our grocery cashier, her workday can be modeled using nested loops. In Programming Activity 1, we wrote the code for our cashier to calculate the total cost of the contents of one customer’s grocery cart. But ...

Get Java Illuminated, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.