Introduction
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
for (initialization; condition; update) { for (initialization; condition; update) { // inner loop code } // outer loop code }
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { std::cout << i << "," << j << " "; } std::cout << std::endl; }
for (int row = 1; row <= 4; row++) { for (int col = 1; col <= 4; col++) { std::cout << "* "; } std::cout << std::endl; }
This program prints pairs of numbers with a star between them, showing how nested loops work together.
#include <iostream> int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { std::cout << i << "*" << j << " "; } std::cout << std::endl; } return 0; }
Remember that the inner loop finishes all its cycles before the outer loop moves to the next step.
Too many nested loops can make your program slow and hard to read.
Nested loops run one loop inside another to handle repeated tasks in rows and columns.
They are useful for grids, tables, and comparing pairs of items.
Keep loops simple and avoid too many levels to stay clear and fast.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// code
}
}for loop inside another for loop, which means nested loops.for(initialization; condition; increment) syntax for loops.for i in range(3): for j in range(2): /* code */ uses Python syntax, invalid in C++.for(int i=0; i<3; i++) { for(int j=0; j<2; j++) { /* code */ } } uses correct C++ syntax with nested for loops.while(i<3) { while(j<2) /* code */ } uses while loops missing initializations and increments.loop(i=0; i<3; i++) { loop(j=0; j<2; j++) { /* code */ } } uses invalid loop keyword.for(int i = 1; i <= 2; i++) {
for(int j = 1; j <= 3; j++) {
std::cout << i*j << " ";
}
std::cout << std::endl;
}for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; i++) {
std::cout << i+j << " ";
}
std::cout << std::endl;
}i++ instead of j++, causing infinite loop or wrong behavior.j to progress through its range.Pass the test and this pattern moves unknown