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

Custom Hook 來自己寫一個  hook 吧!

Custom Hook 來自己寫一個 hook 吧!

用 Nest.js 開發 API 吧 (四) - Service

用 Nest.js 開發 API 吧 (四) - Service

【文章筆記 】CS75 (Summer 2012) Lecture 9 Scalability Harvard Web Development David Malan

【文章筆記 】CS75 (Summer 2012) Lecture 9 Scalability Harvard Web Development David Malan


Comments