C++ Nested Loops


Loops are one of the fundamental concepts in programming. In C++, loops allow a program to execute a set of statements multiple times. Nested loops are simply loops inside other loops. This article will explain what nested loops are, their types, and how to use them in C++ with sample code.

What is a Nested Loop in C++?

A nested loop is a loop within another loop. The inner loop runs completely every time the outer loop executes one iteration. Nested loops can be used to perform repetitive tasks with multiple levels of repetition.

For example:

  • An outer loop iterates through rows.
  • An inner loop iterates through columns.

Nested loops are useful for working with multi-dimensional data structures like matrices, grids, or tables.


Types of Nested Loops in C++

  1. For Loop Nested Inside a For Loop
    • Commonly used for looping through a fixed number of iterations.
  2. While Loop Nested Inside a For Loop or While Loop
    • Used when the number of iterations is uncertain but needs to be checked on each iteration.
  3. Do-While Loop Nested Inside Other Loops
    • Useful when you need to execute the inner loop at least once before checking the condition.

Each type can be used depending on the task you're working on. Let's explore them in more detail with sample code.


Sample Code for Nested Loops in C++

Example 1: Nested For Loop

In this example, we will use a nested for loop to print a multiplication table.

#include <iostream>
using namespace std;

int main() {
    int rows = 5, cols = 5;
    
    // Outer loop for rows
    for (int i = 1; i <= rows; i++) {
        // Inner loop for columns
        for (int j = 1; j <= cols; j++) {
            cout << i * j << "\t"; // Print multiplication result
        }
        cout << endl; // Move to the next line after each row
    }

    return 0;
}

Explanation:

  • The outer loop iterates over the rows (from 1 to 5).
  • The inner loop iterates over the columns (from 1 to 5) and prints the product of the current row and column.
  • The result is a 5x5 multiplication table.

Output:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

Example 2: Nested While Loop

In this example, we use a nested while loop to print a pattern of stars.

#include <iostream>
using namespace std;

int main() {
    int rows = 5, i = 1, j;

    // Outer while loop for rows
    while (i <= rows) {
        j = 1; // Inner loop counter reset
        // Inner while loop for columns
        while (j <= i) {
            cout << "*"; // Print a star
            j++; // Increment the column counter
        }
        cout << endl; // Move to the next line after each row
        i++; // Increment the row counter
    }

    return 0;
}

Explanation:

  • The outer while loop iterates over the rows.
  • The inner while loop prints stars (*) corresponding to the current row number.
  • As the outer loop progresses, the number of stars printed increases.

Output:

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

Example 3: Nested Do-While Loop

In this example, we use a do-while loop to create a simple number pyramid.

#include <iostream>
using namespace std;

int main() {
    int rows = 5, i = 1, j;

    // Outer do-while loop for rows
    do {
        j = 1; // Inner loop counter reset
        // Inner do-while loop for columns
        do {
            cout << j << " "; // Print the column number
            j++; // Increment column counter
        } while (j <= i); // Inner loop condition

        cout << endl; // Move to the next line after each row
        i++; // Increment the row counter
    } while (i <= rows); // Outer loop condition

    return 0;
}

Explanation:

  • The outer do-while loop iterates over the rows.
  • The inner do-while loop prints the column number on each iteration.
  • The result is a pyramid pattern of numbers.

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

When Should You Use Nested Loops?

Nested loops are especially useful when dealing with tasks such as:

  • Working with matrices or multi-dimensional arrays (e.g., 2D arrays).
  • Printing patterns like number pyramids, star patterns, and more.
  • Simulating multi-level repetitive tasks, such as navigating grids in games or simulations.

However, nested loops can increase the time complexity of a program, so it's essential to use them efficiently. As the number of iterations increases, so does the time needed to complete the task.


Common Mistakes When Using Nested Loops

  1. Incorrect Loop Conditions:

    • If the inner or outer loop condition is not set correctly, it may lead to infinite loops or unexpected behavior.
  2. Overloading the CPU:

    • Nested loops with a large number of iterations can lead to performance issues, especially in programs where efficiency is crucial.
  3. Misplacing Increment or Decrement Statements:

    • Make sure that loop counters (i, j) are correctly incremented to avoid skipping or repeating iterations.