C++ Nested for Loop

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program.

Example of Nested for Loop

The below example demonstrates the use of Nested for loop in a C++ program.

C++




// C++ program to demonstrate the use of Nested for loop.
  
#include <iostream>
using namespace std;
  
int main()
{
    // Outer loop
    for (int i = 0; i < 4; i++) {
  
        // Inner loop
        for (int j = 0; j < 4; j++) {
  
            // Printing the value of i and j
            cout << "*"
                 << " ";
        }
        cout << endl;
    }
}


Output

* * * * 
* * * * 
* * * * 
* * * * 

Explanation

The above program uses nested for loops to print a 4×4 matrix of asterisks (*). Here, the outer loop (i) iterates over rows and the inner loop (j) iterates over columns. In each iteration, inner loop prints an asterisk and a space also new line is added after each row is printed.

for Loop in C++

In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.

for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.

Similar Reads

Syntax of for Loop

The syntax of for loop in C++ is shown below:...

Flowchart of for Loop in C++

Flowchart of for Loop in C++...

Examples of for Loop in C++

Example 1...

C++ Nested for Loop

...

Multiple Variables in for Loop

...

C++ Infinite for Loop

...

Range-Based for Loop in C++

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program....

for_each Loop in C++

...