Nested loops
Sometimes it can be necessary to use a loop inside a loop. A loop inside a loop is called a nested loop. Often it is not the best solution to the problem. It could even be a sign of poorly written code (sometimes called "code smell" among programmers), but every now and then it is a perfectly fine solution to a problem.
Here is what it would look like for while
loops:
while (condition 1) {
// code that gets executed as long as condition 1 is true
// this loop depends on condition 1 being true
while (condition 2) {
// code that gets executed as long as condition 2 is true
}
}
Nesting can also be used with for
loops, or with a combination of both for
and while
, or even with all kinds of loops; they can go several levels deep.
An example in which we might use nested loops would be when we want to create an array of arrays. With the outer loop, we create the top-level array, and with the inner loop we add the values to the array...