Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialbrock
5,789 PointsNested Loops Confuse Me
I am confused with how a computer processes nested loops. Specifically with the line
student = students[i];
The variable student is then used in the next line in an "if" statement, that is also compared to an input value. If student has many different values for the corresponding value of "i" then how is it possibly compared in the next "if then" statement. How is it chosen which value of "i" to use to then compare to the user input.
How many times is the "for" statement run for every time that the "while" statement runs?
Why does the code not test for the first value of "i" and see that the "var student" does not match with the user input, skip the "if" statement, then go back to the top of the "while" statement and open up a new alert?
Sorry, lots of questions. Thank you for the help!
1 Answer
Steven Parker
231,248 PointsIt sounds like your confusion starts with what that statement is doing. A single student does not have 'many different values for the corresponding value of "i"'. The value of "I" in the loop selects one specific student. This assignment makes it possible to refer to that student in the following code without using the index again.
Then, for each time the "while" statement runs, the "for" loop will run once for every student in the array. The loop code checks each student to see if their name matches the input. Testing the first value of "I" would just let you know if the input was the name of the first student, but the rest of the loop is needed to test if the input might match one of the other students. The "for" loop ends after every student has been checked for a match.
Does that clear it up?
brock
5,789 Pointsbrock
5,789 PointsAh ok. I get it now. Thank you!