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

[極短篇] SQL injection

[極短篇] SQL injection

JS-[promises篇]-promises 與 Fetch API

JS-[promises篇]-promises 與 Fetch API

前端串串 API

前端串串 API


Comments