Nested Loop

Estimated reading: 2 minutes 152 Views

A nested loop is a loop that is contained within another loop. This means that the inner loop will iterate for each iteration of the outer loop.

Here is an example of a nested loop in C++:

#include <iostream>

using namespace std;

int main()
    for ( size_t i = 1; i <= 5; i++)
        for ( size_t j = 1; j <= 6; j++)
            cout << "*";
        cout << endl;

    return 0;

This code is a nested for loop that prints a rectangle of asterisks to the console. The outer loop iterates 5 times, and the inner loop iterates 6 times. This means that the code inside the inner loop will be executed 30 times.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to 6. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than 6.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 5.

Here is the output of the code:


Nested loops can be used to solve a variety of problems. For example, you could use nested loops to iterate over all the elements of a two-dimensional array, or to generate all the possible combinations of two sets of values.

Here are some tips for using nested loops:

  • Use nested loops sparingly. Nested loops can make your code more difficult to read and understand.
  • Use nested loops to avoid writing duplicate code. If you find yourself writing the same code inside a loop multiple times, consider using nested loops.
  • Use nested loops to make your code more efficient. For example, you can use nested loops to avoid searching for an element in an array multiple times.
Share this

Nested Loop

Or copy link