Help with nested loops

I have no idea on how to make a nested loop and i dont want to move forward until i get them down. Someone please help me understand them. Maybe some line by line examples please.

thank you!

3 Likes

You make a nested loop when you write a loop in the body of another loop. The idea’s pretty simple really.

// For example...
for (var i = 0; i < 10; i++) {

  // This is a nested loop
  for (var j = 0; j < 10; j++) {
    // ...
  }
}

on one like this…I was super confused on. took me 5 hours to complete and understand vaguely what was going on…

1 Like

I think you’re having trouble with arrays that contain arrays.

Say your array is [[1, 2], [3, 4], [5, 6, 7]]. You want to get to the numbers in those inner arrays, but you’ll need a nested loop to do that.

The outer loop iterates through each inner array. Then for the current inner array, the inner (nested) loop iterates through each of its numbers.

So with the outer loop, you access an inner array as arr[i]. Then, since arr[i] itself is also an array, you can get it’s elements by adding a bracketed number after it, like arr[i][0], arr[i][1], etc. You access each of the inner array’s numbers with the inner loop with arr[i][j].

Once you have access to the inner array’s elements, you do what you want to do with it (in this case, multiply it to a variable that accumulates products).

Hope that made sense.

7 Likes

A better coding environment might help. Try this:

https://repl.it/languages/javascript

Paste this:

for (var i = 1; i < 4; i++){
    for (var z = 1; z < 4; z++){
        console.log("Loop one is on: "  + i + ", Loop two is on  " + z)
        // this loop completes all its steps every time the bigger loop does 1 step
    }
}
8 Likes

First time I’ve seen an embedded repl.it. Awesome!

Yeah you just past the URL for a new session - https://repl.it/languages/javascript - on a new line.

thats NICE! HOPE TO BE ABLE TO HELP EACH OTHERS WITH THIS!

1 Like

what does that + i + mean in the sample code?

it means that the value of i in the loop’s current iteration will be included in the output to the console. running this loop would result in:

Loop one is on: 1, Loop two is on 1
Loop one is on: 1, Loop two is on 2
Loop one is on: 1, Loop two is on 3
Loop one is on: 2, Loop two is on 1
Loop one is on: 2, Loop two is on 2
Loop one is on: 2, Loop two is on 3

… and so on, until:

Loop one is on: 3, Loop two is on 3

…so, for each iteration, “Loop one” is displaying the value of i and “Loop two” is displaying the value of z.