Nested Loops in C and C++

Nested-Loops-in-C-and-C-feature-Image.jpg

Imagine you are building a simple 2D game and need to check every tile on a 10×10 grid to detect collisions between your player and obstacles. If you write if-statements for this validation, writing 10 x 10 = 100 if statements will be redundant, hard to maintain, and overall a waste of time. Instead, you could use nested loops. In this article, you will learn how nested loops work in C and C++, the various kinds of nested loops, like the for loop, the while loop, the do-while loop, and their syntax. We will also explore practical examples like 2D matrix operations and pattern printing, understand how outer and inner loops interact, and increase the efficiency of your logic. 

Table of Contents:

What are Nested Loops?

A nested loop in C and C++ is simply a loop inside a loop. When you implement or code one loop inside another loop, it creates a nested loop. It is a programming concept that is used in many programming languages and allows you to perform complex iterations. These loops help a developer do more with their code by implementing combinations and systems that wouldn’t be possible with a simple loop. The nested loops are essential in both C and C++ programming for tasks such as creating patterns, working with multidimensional arrays, and performing matrix operations. Understanding how nested loops work will help you write more efficient code and solve complex programming challenges.

Take Your C Skills to the Next Level!
Unlock Full Access Now and build a solid foundation for competitive programming and technical interviews!
quiz-icon

How Nested Loops Work 

As we know, a nested loop is a loop inside a loop. There are two loops; the loop that contains another loop is called the outer loop, and the loop that is inside is called the inner loop.  Now, let us understand how the nested loops execute and how the outer and inner loops interact.

Nested Loops in C++ flow diagram

Execution Process:

  1. The outer loop starts first, initializing its counter. After initialization, the condition inside the outer loop gets checked.
  2. If the outer loop condition is true, the program enters the loop body for execution.
  3. Inside the loop, the control flow encounters another loop, which is called the inner loop. Now, the inner loop initializes, and if there is no loop inside it, this loop executes completely until the condition inside the inner loop becomes false.
  4. Once all the iterations of the inner loop finish, the control returns to the outer loop.
  5. The outer loop then increments its counter and re-evaluates the condition.
  6. This process repeats until the outer loop condition becomes false, and the control passes to the next line of code. 

Key Points to Remember:

  • The inner loop completes all its iterations for each iteration of the outer loop
  • If the outer loop runs 3 times and the inner loop runs 4 times, the total number of iterations = 3 × 4 = 12
  • Inner loop variables are reinitialized for every outer loop iteration.
Total Number of Times a Loop runs in a nested loops in C++

Types of Nested Loops in C and C++

Three main types of nested loops can be implemented in C and C++. These are for loop, while loop, and do-while loop. You can either use the same loops or different loops for the inner and outer loops. Let us explore each type with its syntax and practical examples.

1. Nested For Loop

The nested for loop is one of the most commonly used nested loop structures. This loop is used when you know the number of times (iterations) both the inner and outer loop needs to run. The syntax for a nested for loop in C and a nested for loop in C++ is the same.

Syntax:

for(initialization; condition; increment/decrement) {
    // Outer loop body
    for(initialization; condition; increment/decrement) {
        // Inner loop body
    }
}

Example of a Nested for loop in C:

C

Output:

Nested For loop in C output

Explanation: In this code example, the nested for loop in C generates a multiplication table using nested for loops. The outer loop picks the first number to be displayed. Then, for each of these numbers, the inner for loop assigns each number that it needs to multiply by, finally printing each product systematically. For each i, the inner loop calculates i * j, and the result is printed as i x j = [value].

Example of a Nested for loop in C++:

C++11 introduced a new iteration method called the range-based for loop, which provides a more user-friendly way to iterate through collection data structures like arrays, vectors, etc. This is a special feature exclusive to the C++ programming language and cannot be found in C.

Cpp

Output:

Nested for loop in C++ output

Explanation: This C++ example demonstrates a range-based for loop iterating over a vector (numbers). This is different than typical loops because it automatically accesses each element without the programmer needing to use the index. The loop prints out all values (1 to 5) and then exits when the last element is processed.

Nested While Loop

A nested while loop consists of an inner and an outer while loop. A while loop does not need a known number of iterations to run. Therefore, a nested while loop is a suitable choice, where the number of iterations depends on dynamic conditions that could change while the program is executing. The following describes the syntax for a while loop in C and C++.

Syntax:

while(condition1) {
    // Outer loop body
    while(condition2) {
        // Inner loop body
        // Statements to execute
    }
}

Example of a Nested while loop in C:

C

Output:

Nested while loop in C output

Explanation: In this example, the outer while loop controls the row value (1 to 3). The inner while loop runs for each row, printing column col from 1 to 3. Then the position of the row and column pair is printed as coordinates. This shows how traversal through the 3 x 3 matrix happens from row to row. For each row, the inner loop iterates fully, printing the position as a coordinate pair. This shows how a 3×3 grid traversal proceeds row by row.

Example of a Nested while loop in C++:

Cpp

Output:

Nested while loop in C++ output

Explanation: Here:

  • The outer loop runs 3 times and hence the outer_loop_counter changes thrice, taking the values 1,2,3 respectively.
  • For each outer iteration, the inner loop runs twice, during which the inner_loop_counter takes two values 1,2.
  • Printing both counters each time, resulting in 6 output lines showing all combinations.

Nested Do-While Loop

The nested do-while loop has an inner and outer loop. A do-while loop always executes once (the do part) before the condition in the while loop gets checked (the while part).

Syntax:

do {    
// Outer loop body
    do {
        // Inner loop body
        // Statements to execute
    } while(condition2);
} while(condition1);

Example:

C

Output:

Nested do while loop in C output

Explanation: In this code, a nested do-while loop is used to print coordinate-like pairs. The outer loop variable i starts from 1 and goes up to 3. For each i, the inner loop variable j starts from 1 and runs up to 2. The output prints all combinations of (i, j) where i = 1 to 3 and j = 1 to 2. Since do-while checks the condition after executing the body, both loops run at least once.

Example:

Cpp

Output:

Nested do while loop in C++ output

Explanation: In this nested do-while example, both the outer and inner loops execute their “do” block at least once. Even though the initial conditions (outer_count < 1, inner_count < 1) become false after the first pass, their bodies run before the while condition is checked. 

Get 100% Hike!

Master Most in Demand Skills Now!

Mixed Nested Loops in C and C++ with Examples

As mentioned previously, mixed nested loops are when you combine different types of loops within one nested loop. In the case of mixed nested loops, you can use any mix of for, while, and do-while loops for either the outer or inner loop. Mixed nested loops allow you to choose the appropriate loop type for each different level, according to your respective conditions, requirements, etc.

While loop with do-while loop in C example:

C

Output:

Mixed Nested Loops in C output

Explanation: In this C code example, our outer loop is a while loop that continues as long as i <= 2. In this loop, we use a do-while loop, which will continue to run at least once, and as long as j<= 3. This example shows how the different types of loops can interact with each other and how the use of nesting can control behavior based on logic requirements.

For loop with a while loop in C++ example:

Cpp

Output:

Mixed Nested Loops in C++ with Examples

Explanation: In this example, we employed a for loop as the outer loop in our code and a while loop as the inner loop. This is an example of Mixed Nested Loops. 

When to Use Mixed Nested Loops

Here are some examples of when you can utilize mixed nested loops to increase the efficiency of your code.

  • You would use mixed nested loops when the outer loop requires dynamic condition checking (while), but the inner loop has fixed iterations (for).
  • Or when the outer loop requires guaranteed execution (do-while), but the inner loop has conditional execution (while).

Solved Examples Using Nested Loops in C and C++

Let us look at a few of the practical situations where nested loops help the developer instead of just plain loops in C/C++ programming.

1. 2D Matrix Operations

Nested loops allow developers to more easily visualize a 2D array or matrix and to perform different calculations on it. Matrix operations are fundamental in domains like scientific computing and graphics. Below is an example of using nested loops to perform calculations on a 2D matrix.

Example:

Cpp

Output:

2D Matrix Operations

Explanation:  In the code above, we took a 3 x 4 matrix and then calculated the cumulative sum of all the elements.

2. Pattern printing

Pattern problems are perfect for sharpening your logical reasoning ability and your problem-solving skills, as they are typically asked in interviews, as well as help you prep for other questions, even if they don’t specifically mention patterns. With that being said, nested loops make it easy to solve some of these problems. Let’s go over an example of an inverted triangle star pattern being solved using nested loops in C++.

Example: We need to print the following pattern.

Pattern printing example
Cpp

Output:

Pattern Printing output

Explanation: This C++ code is using nested loops: one loop for rows (i) and another for columns (j) to create a hollow inverted triangle. Regarding the inner loop, we only print a star (*) at each (i, j) positions given certain conditions: if we are in the first (solid) row (i==0), the one star in the last row (i == n_rows – 1 and j is in the middle), and the left and right diagonal sides of the triangle (j == i for the left-side edge or (j == max_width – 1 – i for the right-side edge) in intermediate rows; otherwise, we print space ( ).

When to Use Nested Loops

Let us look at some common real-world scenarios other than matrices and pattern problems, where using nested loops in C++ and C is the best practice.

  • Game Development: One of the most common real-world examples of nested loops will be in game development. In game development, you’re adding a layer of complexity in managing a game board, grid, or tile system, where you need to examine and process each cell logically with a nested loop.
  • Combinatorial Problems: Combinatorial problems are problems that involve producing all possible combinations or permutations of items among different sets. In this situation, nested loops will be your best solution.
  • Search Operations: Also, searching through multi-dimensional data structures or those that include comparison with elements in another dataset will include nested loops for clearly defined logic and results.
  • Mathematical Computations: Another situation for using nested loops would be for calculations involving multiple variables or repeated iterations, such as matrix multiplication or statistical analysis.

Common Mistakes to Avoid in Nested Loops

When working with nested loops, programmers often make these mistakes:

  • Infinite Loops: This is the most common mistake that even practiced programmers make. Always ensure that there is a break statement or a loop condition that will eventually become false and stop the loop from running. Forgetting to increment or decrement loop variables may also lead to infinite loops.
  • Variable Scope Confusion: This is another common mistake that programmers fail to pay attention to. Don’t use the same variable name for both outer and inner loop counters. This creates scope issues and unexpected behavior.
  • Incorrect Loop Bounds: Pay attention to the loop starting and ending conditions. Usually, the conditions are off by one, and these errors are common in nested loop structures.
  • Performance Issues: Nested loops can be computationally expensive. Do not use them for large datasets, and consider using alternative approaches or optimizing your algorithm.
  • Logic Errors in Conditions: Make sure your loop conditions align with your intended logic. This you can be sure of only after running your logic once, therefore, start and test with small inputs first.

Conclusion

Nested loops in C and C++ can be extremely useful when you want to do something many times within another repeated action. In a nested loop, one loop executes completely within another loop. In this article, we discussed many examples that will build your confidence when creating your nested loops and help you understand some common errors and help you avoid them, for example, entering an infinite loop. Deeply nested loops can slow down your program, especially with large datasets. Therefore, use nested loops where it would not affect the performance. You can utilize nested loops effectively in both C and C++ programming languages by learning to use them with the proper variable types.

Nested Loops in C and C++ – FAQs

Q1. What is a nested loop in C++ and C?

You can use a nested loop when one loop runs inside another. It’s useful for tasks like printing patterns or working with 2D arrays.

Q2. Can you name different types of nested loops in C++ and C?

Yes, you can nest for, while, or do-while loops inside each other in any combination, based on your logic requirements.

Q3. Where are nested loops used in C and C++?

You can use nested loops in C++ and C for matrix operations, pattern printing, games, and multi-dimensional data traversal.

Q4. How does a nested while loop in C differ from Python?

In C/C++, while loops require explicit initialization and increments (e.g., i++), whereas Python uses indentation and optional else clauses.

Q5. Do nested loops affect performance in C++ and C?

Yes, you should know that nested loops increase time complexity. Optimise them to avoid slow execution, especially in large datasets.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner