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

筆記:我知道你懂 hoisting,可是你了解到多深?

筆記:我知道你懂 hoisting,可是你了解到多深?

React-[入門篇]- 渲染列表 (rendering lists) |解構props寫法

React-[入門篇]- 渲染列表 (rendering lists) |解構props寫法

r3:0 異世界網站挑戰攻略與心得

r3:0 異世界網站挑戰攻略與心得


Comments