Nested Loops

The placing of one loop inside the body of another loop is called nesting. When you, “nest” two loops, the outer loop takes control of the number of complete repetitions of the inner loop. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

A Nested for loop (in most computer programming languages), takes the generic form of:

FOR counter1 in range(n)
FOR counter2 in range(m)
statement(s)
END
END

or using While loops:

WHILE counter1 <= n :
WHILE counter2 <= m :
statement(s)
counter2 = counter2 + 1
END
counter2 = 0
counter1 = counter1 + 1
END

In this example program, the output shows a 2 digit odometer, using a Nested loop.

Top-Down Design for Nested loops

Top-Down Design for Nested Loops

Flowchart for Nested loops

for Nested Loops flowchart

Pseudocode for Nested loops

FOR counter1 in range(10)
FOR counter2 in range(10)
SHOW Odometer {counter1}{counter2}
END
END

Code for the Nested loops

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a nested loop

#include <stdio.h>

int main() {
    // this function uses a nested loop

    // process & output
    for (int counter1 = 0; counter1 < 10; counter1++) {
        for (int counter2 = 0; counter2 < 10; counter2++) {
            printf("Odometer: %d%d\n", counter1, counter2);
        }
    }

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a nested loop

#include <iostream>

int main() {
    // this function uses a nested loop

    // process & output
    for (int counter1 = 0; counter1 < 10; counter1++) {
        for (int counter2 = 0; counter2 < 10; counter2++) {
            std::cout << "Odometer: " << counter1 << counter2 << std::endl;
        }
    }

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested loop
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function uses a nested loop

        // process & output
        for (int counter1 = 0; counter1 < 10; counter1++) {
            for (int counter2 = 0; counter2 < 10; counter2++) {
                Console.WriteLine("Odometer: " + counter1 + counter2);
            }
        }

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested loop
 */

package main

import (
	"fmt"
)

func main() {
	// this function uses a nested loop

	var counter1 int
	var counter2 int

	// process & output
	for counter1 < 10 {
		for counter2 < 10 {
			fmt.Printf("Odometer:%d%d\n", counter1, counter2)
			counter2++
		}
		counter2 = 0
		counter1++
	}

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
 * This program uses a nested loop
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

public class Main {
  public static void main(String[] args) {
    // this function uses a nested loop

    // process & output
    for (int counter1 = 0; counter1 < 10; counter1++) {
      for (int counter2 = 0; counter2 < 10; counter2++) {
        System.out.println("Odometer: %d%d".formatted(counter1, counter2));
      }
    }

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a nested loop
 */

// process & output
for (var counter1 = 0; counter1 < 10; counter1++) {
  for (var counter2 = 0; counter2 < 10; counter2++) {
    console.log(`Odometer: ${counter1}${counter2}`)
  }
}

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses a nested loop
"""
import time


def main() -> None:
    """The main() function uses a nested loop, returns None."""

    # process & output
    for counter1 in range(10):
        for counter2 in range(10):
            print(f"Odometer: {counter1}{counter2}")
            time.sleep(0.25)

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output