Nested Loops and Increment

2

I am 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>")
}
    
asked by anonymous 10.11.2018 / 21:18

1 answer

2

In order to achieve this goal, you only need to change the stop condition in the% of columns%, so that it stops at the number after the current line.

You can see this:

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

And so on.

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 have the method for " of the string that does this, which greatly simplifies logic:

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