Language: EN

programacion-anidacion-bucles

Loop Nesting

Nesting loops is a control structure that consists of putting loops inside other loops.

Here loop can be any of the ones we have seen: WHILE, DOWHILE, FOR, FOREACH, depending on what our language has available.

Nesting loops is especially useful (and necessary) when it is required to iterate over complex data structures or when repetitive operations need to be performed at different levels of hierarchy.

By putting one loop inside another loop, we will have a structure like the following:

programacion-loop-nested

Nested loops diagram
  • The outer loop will be the loop that encloses other loops.
  • Inside it, we define the inner loop.

Which translated into code, would look like this:

loop(...) // outer loop 🔵
{
	// Actions that occur before the inner loop
	  
    loop(...)  // inner loop 🟨
    {
        // Action that repeats in the inner loop
    }
    
    // Action that occurs after the outer loop
}

When the code is executed:

  • First, the outer loop 🔵 is executed.
  • The lines before the inner loop 🔵 are executed.
    • Upon reaching the inner loop 🟨, the code gets “stuck there looping” 🔁.
  • Once the inner loop finishes, the remaining lines of the outer loop 🔵 are executed.
  • When reaching the end of the outer loop, it repeats 🔁.

Examples of nesting conditionals in different languages

Let’s see an example in different programming languages on how to perform a nesting of loops:

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 3; j++)
    {
        // Action that repeats in the inner loop
    }
    // Action that repeats in the outer loop
}
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 3; j++)
    {
        // Action that repeats in the inner loop
    }
    // Action that repeats in the outer loop
}
for (let i = 0; i < 5; i++)
{
    for (let j = 0; j < 3; j++)
    {
        // Action that repeats in the inner loop
    }
    // Action that repeats in the outer loop
}
for i in range(5):
    for j in range(3):
        # Action that repeats in the inner loop
    # Action that repeats in the outer loop

In these examples, we have performed a loop of type FOR, with:

  • 5 repetitions of the outer loop
  • 3 repetitions of the inner loop

This means that, in total:

  • The outer loop repeats 5 times
  • The inner loop repeats 5 x 3 = 15 times.

Best practices Tips

Nesting loops is common, and necessary to solve complex problems (especially in structured and grouped data).

For example, imagine the following code, which simulates evaluating all students in a class.

foreach(classroom)
{
   foreach(student in classroom)
   {
      evaluate_student(student)
   }
}

If I have to perform that calculation for all classrooms and all students in each of them, a nested loop is the simplest solution.

However, nesting loops also has its problems. The main one is that the number of loops we execute increases exponentially.

If, for example, you have a loop that executes 10,000 times, inside a loop that executes 10,000 times, the inner loop will execute 100 million times!

for(10000)
{	  
    for(10000)
    {
        // this will execute 100,000,000 times!!
    }
}

Now imagine if you put another loop inside… ⌛⌛⌛ … In other words, don’t get too carried away nesting loops inside loops.

Another problem is that in WHILE loops, it can complicate the exit condition. It’s easier to get stuck in an infinite loop.

The last issue is that it can make the code more complex to understand. For example, the previous example could be easier to understand if we “split” the function evaluate_student and evaluate_classroom.

foreach(classroom)
{
   evaluate_classroom(classroom)
}

function evaluate_classroom(classroom)
{
   foreach(student in classroom)
   {
      evaluate_student(student)
   }
}

As always, it’s important to maintain a clear and readable code structure, so that it is easy to understand for you or for the next person who reads it.