Language: EN

programacion-anidacion-bucles

Loop Nesting

Loop nesting is a control structure consisting of putting loops inside other loops.

Here loop can be any of those we have seen WHILE, DOWHILE, FOR, FOREACH, according to what our language has available.

Loop nesting is especially useful (and necessary) when it is required to iterate over complex data structures or when repetitive operations are needed at different levels of hierarchy.

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

programacion-loop-nested

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

When translated to code, it would look like this:

loop(...) // outer loop 🔵
{
	// Actions that occur before the inner loop
	  
    loop(...)  // inner loop 🟨
    {
        // Action that is repeated 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.
    • When reaching the inner loop 🟨, the code is “trapped there, going around” 🔁.
  • After 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 programming languages

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

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

In these examples, we have performed a FOR loop 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.

Cleaning tips Tips

Loop nesting is common and necessary for solving complex problems, especially in structured groupings.

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

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

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

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

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

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

Now imagine if you nest another loop inside… ⌛⌛⌛ … In other words, don’t get carried away by putting loops inside loops.

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

The last problem is that it can be more difficult to understand code. 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 is 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.