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 trialVincent Day
578 PointsHow do we know to use a 'for in' loop here.
I'm not certain how we are to know that a 'for in' loop is supposed to be used.
3 Answers
Brenden Konnagan
16,858 PointsAs Amit says in the video there are multiple ways to address this problem. The old saying: "There is more than one way to skin a cat..." is applicable here.
Personally when I did the challenge I approached it much different, but still arrived at the same results.
The advantage of using a for - in loop here is that it concisely allows the iteration through a range of numbers.
However, it should be understood that there is not a "right" way to accomplish this assignment. And over time you will develop your own prefrence to coding and will develop skills in refacturing your code to gain effeciency and clearity.
I hope this helps.
truemaulik
Courses Plus Student 7,765 PointsWhen you are sure about how many times you want the code to loop again & again, For example: if you want to print the five numbers (1,2,3,4,5) , then you are sure that you want to loop through the code 5 times so in this case we should use simple for loop.
But, if we want to print each number stored in an array, then we are not sure , how much times we need to loop through the code because we don't know the total numbers stored in an array.(if the array has tens of thousand of numbers then there is no need for us to count that leave it to the for in loop ) so in this case we should use for in loop.
Vincent Day
578 PointsGreat answer! Moving forward I'll know to use a for loop when the number of times the loop needs to run is specified, otherwise the for in loop makes more sense.
truemaulik
Courses Plus Student 7,765 PointsVincent Day when the size of array is changing or might change -> in that case it's always best to use for in loop.
Vincent Day
578 PointsVincent Day
578 PointsDefinitely helpful. My take away from your responses is that the for in loop works when using a range of numbers. Thanks!