Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

MTR04_0930

MTR04_0930

MAC PHP執行發生錯誤 在 Chrome 上顯示 Error 500

MAC PHP執行發生錯誤 在 Chrome 上顯示 Error 500

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

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


Comments