Nested loops and incrementation

Asked

Viewed 39 times

2

I’m studying Javascript by code house book and has a challenge involving nested loops, in which I have to draw this:

*
**
***
****
*****
******
*******

Using this code:

for(var Linha=0;Linha<10;Linha=Linha+1){
    for(var Coluna=0;Coluna<10;Coluna=Coluna+1){
        document.write("*")
    }
    document.write("<br>")
}

1 answer

3

To achieve this goal you only need to change the stop condition on for of the columns, to stop at the number after the current line.

You can visualize like this:

  • In the first line, line 0, goes up to 1 and writes 1 caretere
  • In the second, line 1, goes up to 2, and so write 2 careteres

And so on and so forth.

Example:

for(var Linha=0;Linha<10;Linha=Linha+1){
    for(var Coluna=0;Coluna<Linha + 1;Coluna=Coluna+1){
        //                    ^--- Linha + 1 em vez de 10
        document.write("*")
    }
    document.write("<br>")
}

In fact as you just want to repeat the asterisks a certain amount of times already has the method repeat of the string that does this, which greatly simplifies the logic:

for(var Linha=0;Linha<10;Linha=Linha+1){
    document.write("*".repeat(Linha + 1) + "<br>")
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.