Table of Contents
A nested loop is a loop placed inside the body of another loop. The inner loop executes completely for each iteration of the outer loop.
Nested loops are commonly used when working with two-dimensional data, generating tables, processing matrices, and performing repeated operations across multiple dimensions.
Source Code #
#include <iostream>
int main()
{
for (int row = 1; row <= 3; ++row)
{
for (int column = 1; column <= 4; ++column)
{
std::cout << row << "," << column << " ";
}
std::cout << '\n';
}
return 0;
}
Output #
1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
Explanation #
- The outer
forloop controls the value ofrow. - The inner
forloop controls the value ofcolumn. - For every iteration of the outer loop, the inner loop executes all of its iterations.
- When
rowis1, the inner loop runs withcolumnvalues from1through4. - The outer loop then increments
rowto2, and the inner loop starts again fromcolumn = 1. - This process continues until the outer loop condition becomes
false. - The inner loop is completely executed before the outer loop proceeds to its next iteration.
- Nested loops can contain other loop types, such as
whileordo-whileloops. return 0;terminates the program successfully.