Comp 101 Nested Loops

Nested Loops

Did you know we can put loops within loops? That's right, LOOPCEPTION!!!!

Let's take a look at how we might set this up.

```for(let i = 0; i < 5; i++){
for(let j = 0; j < 3; j++){
print("I love COMP101!!! ");
}
}```

The above loop will print: "I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! I love COMP101!!! "

If you count those up that's 15 times! that's because the interior loop's counter variable (j) will reset to 0 each time the outer loop's counter variable (i) resets.

Let's take another look at this concept.

```for(let i = 0; i < 5; i++){
print("I is: " + i)
for(let j = 0; j < 3; j++){
print(j);
}
}```

This example will print:

I is: 0

0 1 2

I is: 1

0 1 2

I is: 2

0 1 2

I is: 3

0 1 2

I is: 4

0 1 2

Let's break down what's happening here. When we first enter the outer for loop "I is: value_of_i" is printed. Then we enter the inner for loop where the values of j 0,1 and 2 are printed on each iteration. Note that the "I is:" phrase is not repeated each time the inner loop runs because it is outside of the inner loop, meaning it is only repeated when the outer loop iterates.

Use with 2D Arrays

Nested loops are especially useful when working with 2D arrays! Let's look at an example of how we would iterate through an entire 2D array using nested for loops.

``````let nums = [];
nums[0] = [1,2,3,4];
nums[1] = [5,6,7,8];
nums[2] = [9,10,11,12];
nums[3] = [13,14,15,16];

for(let col = 0; i < nums.length; i++) {
for(let row = 0; j < nums[col].length; j++) {
nums[col][row] = nums[col][row]++;
}
}``````

In the above example we use our outer loop with counter variable col to iterate through the columns in our array - this helps us isolate which column we want to look at. Once we've selected which column we want to look at (let's say col 0 so [1,2,3,4]) we then want to isolate one specific element to work with. This is where our second loop comes in handy! the second loop iterates from 0 to nums[col]'s length - allowing us to access each element in that column. This process repeats until we've worked our way through the entire 2D array!