Print lots of stars


Posted by Christy on 2022-04-19

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);









Related Posts

Git 速記

Git 速記

MTR04_0825

MTR04_0825

4. 安裝與使用第三方套件

4. 安裝與使用第三方套件


Comments