For loops

Hi everyone! Can someone help me to produce the following outputs with for loops in JS? Thank you very much in advance

  • 1 1 1 2 2 2 3 3 3 4 4 4
    for(let e = 1; e <= 4; e++ )???

  • 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
    for(let f =0; f<=4; f++)???

Hello @delafuentej, welcome to the forums! Both of these solutions require nested loops. Consider how you want the numbers to repeat. Now, try to do it on paper and pencil, and try to write some instructions on how to do it manually. Then try to turn these instructions into code. If you have any more questions, feel free to ask!

Hi @delafuentej!

Actually you are pretty close to the solution. As @codeneutrino mentioned, you need to use nested loops to solve the problem. Just in case you do not know what he meant with that, nested loops is when you have a loop inside another loop. For example see the following:

for(...){
   for(...){
      //Enter your code here
   }
}

Now, you have already one of the loops needed. Try figuring out what the other loop must be and in which order you must put them to accomplish those outputs.

Tell us if you could find the solution by your own, we can give you more hints if you still need them.

Happy coding!


If you found the solution helpful and made you solve your problem, don’t forget to assign the post as the solution. This way, you could help others who have the same problem as you do.

Thank you very much for the advice (@didash @codeneutrino) If you have any other possible solutions, please let me know. I post my solution to the problem:

  • 1 1 1 2 2 2 3 3 3 4 4 4 ==> NESTED LOOPS

{
    for(let f =1; f<=4; f++){
        for(let g =0; g<=2; g++){
            console.log(f); 
        }
    }
}
  • 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
{
    for(let w =0; w<=2;w++){
        for(let w=0;w<=4;w++){
            console.log(w);
        }
    }
}

Good job @delafuentej! I am glad we helped. The only thing I would recommend is that you use different variable names for each index (I am talking about your second code snippet), as it might be confusing or unclear which variable you are referring to. Even more when they have to interact with each other. Despite of that, very well done!

1 Like