Description: Write a function named stars that accepts a number n and print the star patterns like below.
Note: Don’t use repeat()
stars(1)
*
stars(3)
*
**
***
stars(7)
*
**
***
****
*****
******
*******
Let's dismantle this question here, print a row of star first like below:
function stars(n) {
let star = "";
for (let i = 1; i <= n; i++) {
star += "*";
}
console.log(star);
}
stars(3); // ***
Every line is a for loop and there're three lines so do a for loop again
function stars(n) {
for (let i = 1; i <= n; i++) {
let star = "";
for (let j = 1; j <= i; j++) {
star += "*";
}
console.log(star);
}
}
stars(3);
Reflection:
n equals the times of output, if n = 3, the output is 3
Every output has the count of stars
it’s a for loop inside a for loop
Another answer:
function stars(n) {
let star = "";
for (let i = 1; i <= n; i++) {
console.log((star += "*"));
}
}
stars(3);