C++ Code Example: double nested for-loop

Here the product of the individual loop elements is output in a double nested loop.

The program contains three nested for loops, each with its own control variable: i, j, and k.

The outermost loop, for (int i = 3; i < 5; i++), starts with i equal to 3 and increments i by 1 until i is no longer less than 5. So, this loop runs 2 times.

The middle loop, for (int j = 1; j < 10; j++), starts with j equal to 1 and increments j by 1 until j is no longer less than 10. So, this loop runs 9 times for each iteration of the outer loop.

The innermost loop, for (int k = 1; k < 5; k++), starts with k equal to 1 and increments k by 1 until k is no longer less than 5. So, this loop runs 4 times for each iteration of the middle loop.

For each iteration of the innermost loop, the int result variable is declared and assigned the value of i * j * k. The value of result is then printed to the console using cout << result << " ";. After each iteration of the innermost loop, a new line is started using cout << endl;.

After each iteration of the middle loop, another new line is started using cout << endl;.

Finally, the program returns 0, indicating that it has executed successfully.

#include <iostream>
using namespace std;

int main() {
    for (int i = 3; i < 5; i++) {
        for (int j = 1; j < 10; j++) {
            for (int k = 1; k < 5; k++) {
                int result = i * j * k;
                cout << result << " ";
            }
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}
Output
3 6 9 12 
6 12 18 24 
9 18 27 36 
12 24 36 48 
15 30 45 60 
18 36 54 72 
21 42 63 84 
24 48 72 96 
27 54 81 108 

4 8 12 16 
8 16 24 32 
12 24 36 48 
16 32 48 64 
20 40 60 80 
24 48 72 96 
28 56 84 112 
32 64 96 128 
36 72 108 144