A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew.
Listing 5.8 presents a program that uses nested for loops to display a multiplication table.
Listing 5.8 MultiplicationTable.cpp
1 #include <iostream>
2 #include <iomanip>
3 using namespace std;
4
5 int main()
6 {
7 cout << ” Multiplication Table\n”;
8 cout << “——————————–\n”;
9
10 // Display the number title
11 cout << ” | “;
12 for (int j = 1; j <= 9; j++)
13 cout << setw(3) << j;
14
15 cout << “\n”;
16
17 // Display table body
18 for (int i = 1; i <= 9; i++)
19 {
20 cout << i << ” | “;
21 for (int j = 1; j <= 9; j++)
22 {
23 // Display the product and align properly
24 cout << setw(3) << i * j;
25 }
26 cout << “\n”;
27 }
28
29 return 0;
30 }
The program displays a title (line 7) on the first line and dashes (-) (line 8) on the second line. The first for loop (lines 12-13) displays the numbers 1 through 9 on the third line.
The next loop (lines 18-27) is a nested for loop with the control variable i in the outer loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner loop, with j being 1, 2, 3, … , 9. The setw(3) manipulator (line 24) specifies the width for each number to be displayed.
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.