Correct Answer on 7.5 For Loops Inside For Loops but why?


#1

This returns, the correct answer, "Match: 2" but I'm not able to follow the logic of why exactly this works or how I could abstract it.

How do the values for i and j come to equal each other? How does i equal the correct position for the match?

var myPlaces = ['1', '2', '3'];
var friendPlaces = ['a', 'b', '2'];

for (var i = 0; i < myPlaces.length; i++) {
    
  
  for (var j = 0; j < friendPlaces.length; j++) {
        
    
    if (myPlaces[i] === friendPlaces[j]) {
    			console.log('Match: ' + myPlaces[i]);
				}
    }
}


#2

// Bad answer, see answer below.


#3

Hi @java-jumper-eelrj,
There are two loops and one control flow clause.

You can see the first loop should loop 3 times.
The internal loop also loop 3 times.

As first time it loops (outer loop), myPlaces[i] gets some value..(value at i =0)
then when it enters in second loop and it loops 3 times (j = 0 ,j = 1, and j =2) and checks if myPlaces[i] is equal to any value of friendPlaces[j].

same thing happens for i = 1 and it goes to inside loop and checks if value at j =0 , j= 1 , j= 2 is equal or not...and again

...same thing happens for i = 2 and it goes to inside loop and checks if value at j =0 , j= 1 , j= 2 is equal or not

so for one outer loop -- > 3 looping is going inside.
total 9 internal loopings and 3 outer loopings
so it finds one the match that is 2.

If you want to visualize the code in more explicit way..
use this site.. http://www.pythontutor.com


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.