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

發生 Blocking 了!! 怎麼辦?

發生 Blocking 了!! 怎麼辦?

JS註冊組|基本資料型態、變數|JavaScript新手學習筆記

JS註冊組|基本資料型態、變數|JavaScript新手學習筆記

【譯】Tokio 內部機制:從頭理解 Rust 非同步 I/O 框架

【譯】Tokio 內部機制:從頭理解 Rust 非同步 I/O 框架


Comments