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

C++




Example: Showing Motorcycle Brands and Models

C++

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:

C++




Example: Generating a Grid of Bike IDs

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

C++

How It Works

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

Output:

C++

Tutorials dojo strip