Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript The Solution

Can't use a for loop to generate random num between 0 and 9 until getting 8?

In these practice problems, the doWhileLoops, whileLoops, and forLoops follow the basic pattern of exercises (same problems to solve). EXCEPT the forLoop doesn't involve the same 5th loop exercise of generating random numbers between 0 and 9 until you inevitably end in 8 (this exercise is in both of the other loop practice problems). So i'm wondering if it is even possible to create a forLoop to solve this problem. I tried, but couldn't get mine to work and am curious if it's possible. I'm new, so it very well could be simple and I'm just missing it :P Thanks guys! Here's the code I tried but didn't work for the solution in the console: for (let i = Math.floor(Math.random() * 10); i !== 8; i = Math.floor(Math.random() * 10)) { text += i + ' '; }

3 Answers

I'm not sure if this is what you are after but I used an infinite loop and break statement as follows:

for (i = 0; i >= 0; i++){
  j = Math.floor(Math.random() * 10);
  console.log(j);
  if (j === 8){ break;}
}

I don't think I'm sure what the point of the i variable here is. If you loop runs based only on J.

Ali Abbas
Ali Abbas
2,097 Points

Hey Christopher,

This is just a great example of how each loop is suitable for particular tasks. When it comes to the for loops, there's no way of performing this task because it requires 3 arguments to work.

for (i = variable; i = condition; i = i + increments)

main problem here is that while using the for loop, you don't want to increment the random number. So, for this reason the for loop wouldn't be suitable for this task. I hope this helps, take care.

I have written the code exactly as Joel has done (whileLoops Question 5 - Yes, I watched the solution) but, my number 8 is never printed, but Joels number 8 prints, then terminates. I wonder why?

i = Math.floor(Math.random() * 10);
while ( i !== 8 ) {
  text += i + ' ';
  i = Math.floor(Math.random() * 10);
}
text += i;

You might be missing that very last line.

If the loop condition (i.e. i !==8) is met it will terminate, so you need that line outside of the loop body to concatenate the value of i to the text string.