Print * for n number of times


Posted by Christy on 2022-04-19

Description: Write a function that accepts a number n and prints * for n number of times

function star(n) {

}

star(1); // *
star(5); // *****
star(10); // **********

Let's dismantle this question here, I would like to print just five stars:

let result = "";
for (let i = 1; i <= 5; i++) {
  result += "*";
}
console.log(result);
// *****

Secondly I will wrap above into a function and replace 5 to n:

function star(n) {
  let result = "";
  for (let i = 1; i <= n; i++) {
    result += "*";
  }
  console.log(result);
}

star(1); // *
star(5); // *****
star(10); // **********

What I have learned in this practice is when I see the question "Write a function that accepts a number n and prints * for n number of times", don't start to write a function at the first beginning but do the minimal demand from the question step by step, then I will know how to do it.










Related Posts

用 JavaScript 學習資料結構和演算法:字典(Dictionary)和雜湊表(Hash Table)篇

用 JavaScript 學習資料結構和演算法:字典(Dictionary)和雜湊表(Hash Table)篇

[學學ReactNative] DAY2 - AI建議我從這開始!

[學學ReactNative] DAY2 - AI建議我從這開始!

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 7

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 7


Comments