A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop. The outer loop always executes first, and the inner loop executes inside the outer loop each time the outer loop executes once. Take a look at the example below and visualize how the nested loop works.
The sample code above runs the outer loop and the inner loop four times each. The program prints the numbers 1-3 4 different times. The inner loop prints the individual digits while the outer loop determines how many times this task is repeated. Try changing
counter < 4 to
counter < 1. The numbers 1 through 3 should only be printed once if this change is made. This is because the outer loop is only executed once. If the
break; statement existed in the inner loop, it will only exit the inner loop, not the outer loop.