How do I use nested replicates to do this example?

4
*
**
***
****
*****
******
*******
********
*********
**********

How do I do this with nested repeats using% of JavaScript, or in VisuAlg?

For you to have an idea of what the code would look like:

    for(var linha = 0; linha < 10; linha = linha++) {
         for(var coluna = 0; coluna < 10; coluna = coluna++) {          Document.write("*"); 
}
 Document. Write("");
 }

So, but I can not think of anything to give that effect using two loop

    
asked by anonymous 12.09.2016 / 23:05

2 answers

10

If you want to do this with JavaScript you can do this:

var string = [];
for (var i = 0; i < 20; i++) {
    var stars = Array.apply(null, Array(i)).map(function(){return '*'});
    string.push(stars.join(''));
}
document.body.innerHTML = string.join('<br>');

This creates 20 rows within an array and then you can join a string to HTML with <br> between each row for the line break.

A more modern version of JavaScript might be:

const string = [...Array(20)].map(
    (u, i) => [...Array(i)].map(() => '*').join('')
);
document.body.innerHTML = string.join('<br>');

Or using the new method .repeat as indicated in the other answer :

const string = [...Array(20)].map((u, i) => '*'.repeat(i));
document.body.innerHTML = string.join('<br>');

Note:

After reading the comment you wrote , I leave a version also with 2 for loops, if you prefer to use this:

var linhas = 20;
var texto = []
for (var i = 0; i < linhas; i++) {
	var string = '';
	for (var j = 1; j <= i; j++) {
		string += '*';
	}
	texto.push(string);
}
document.body.innerHTML = texto.join('<br>');
    
12.09.2016 / 23:19
9

You can use String.repeat to repeat a sequence according to the current iteration of loop :

for (var contagem = 1; contagem < 11; contagem++) {
    console.log("*".repeat(contagem));
}

To do the same on two nested loops, do so:

var linhas = 11;

for (var linha = 1; linha < linhas; linha++) { // 1 até 11
   for (var coluna = linha; ; coluna++) {      // De 1 até 11, porém sem condição
       console.log("*".repeat(coluna));
       break; // Interrompe o segundo loop
   } 
}

The first for will repeat the code until the current iteration reaches the value of linhas . The second for will only follow the first because a condition was not specified to repeat your code.

    
12.09.2016 / 23:19