4. Nested Loop
Nested
loops are a type of loop that is made up of many loops. The most popular type
of nested loop is one loop within another. “Outer loop” is the first loop and
the “inner loop” is the second loop. The outer loop executes first, followed by
the inner loop, which executes inside the outer loop each time the outer loop
runs.
Syntax:
Let us look at the example below:
for (counter = 1; counter < 4; counter++) {
for (counterTwo = 1; counterTwo < 6; counterTwo++){
Output:
The sample code runs the outer loop and the inner loop five times each and the numbers 1-5 are printed 3 different times. The individual digits are printed by the inner loop, while the outer loop determines how many times this task is repeated. Trying to change the counter from < 4 to < 2, the numbers 1 through 5 should only be printed once if this change is made. This is because it only executes the outer loop once. Only the inner loop, not the outer loop would exit if the break; statement occurred in the inner loop.
The next two example codes below show the nested for a while loop and a do while loop that will generate the same output as the example codes above.
Nested while loop example:
counter = 1;
while (counter < 4) {
counter++;
counterTwo = 1;
while (counterTwo < 6) {
counterTwo++;
Nested do while loop example:
counter = 1;
do {
document.write("Count from 1 to 5" + "<br />");
counter++;
counterTwo = 1;
do {
document.write( counterTwo + "<br />");
counterTwo++;
} while (counterTwo < 6)
} while (counter < 4)
