C++ Nested Loops

In C++, you can place one loop inside another. This is known as a nested loop. Nested loops are especially useful for working with multi-layered structures like tables, matrices, or multi-dimensional arrays.

Tutorials dojo strip



How Nested Loops Work

In a nested loop setup:

  • The outer loop controls the overall iterations.
  • For each iteration of the outer loop, the inner loop runs its entire sequence.




Syntax

for (initialization; condition; update) {  
    for (initialization; condition; update) {  
        // Code to execute in inner loop  
    }  
}




Example: Showing Motorcycle Brands and Models

#include <iostream>
using namespace std;

int main() {
    for (int brandIndex = 1; brandIndex <= 2; ++brandIndex) {  // Outer loop (brands)
        cout << "Brand: " << brandIndex << "\n";
        for (int modelIndex = 1; modelIndex <= 3; ++modelIndex) {  // Inner loop (models)
            cout << " Model: " << modelIndex << "\n";
        }
    }

    return 0;
}

Explanation

  • The outer loop (brandIndex) iterates twice, representing two brands.
  • The inner loop (modelIndex) runs three times for each brand.
  • Together, the nested loop produces six outputs—three models for each of two brands.

Output:

Brand: 1  
 Model: 1  
 Model: 2  
 Model: 3  
Brand: 2  
 Model: 1  
 Model: 2  
 Model: 3  




Example: Generating a Grid of Bike IDs

Nested loops can also create patterns, grids, or formatted outputs.

#include <iostream>
using namespace std;

int main() {
    for (int row = 1; row <= 2; ++row) {  // Outer loop (rows)
        for (int column = 1; column <= 3; ++column) {  // Inner loop (columns)
            cout << "BikeID[" << row << "," << column << "] ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

  • The outer loop (row) controls the rows (2 iterations).
  • The inner loop (column) generates the columns (3 iterations per row)

Output:

BikeID[1,1] BikeID[1,2] BikeID[1,3]  
BikeID[2,1] BikeID[2,2] BikeID[2,3]  

Tutorials dojo strip
Scroll to Top