-2

var i, j;
for (i = 1; i <= 19; i++) {
  for (k = 1; k <= i; k++) {
    document.write("*");

  }
  document.write("<br/>");
}
<div id="output"></div>

Trying to create this pattern and not sure of the best way of how to get it decrement after 10th row:

*
**
***
****
*****
******
*******
********
*********
**********
*********
********
*******
******
*****
****
***
**
*
Harun Yilmaz
  • 6,857
  • 3
  • 21
  • 31
dbork
  • 11
  • 1
    See this, seems duplicate - https://stackoverflow.com/questions/28365737/how-to-print-star-pattern-in-javascript-in-a-very-simple-manner#:~:text=23%20Answers&text=for%20(var%20i%20%3D%207%3B,and%20without%20using%20the%20function.&text=This%20is%20the%20simplest%20solution,using%20only%20one%20for%20loop. – Nikhil Singh Aug 26 '20 at 14:41
  • Instead of looping from 1-19, maybe loop from 1-10 and then from 9-1? – David Aug 26 '20 at 14:42

2 Answers2

1

First increase the loop from 1 to 10 then make a loop that decreases from 9 to 1.

const max = 10;

for (let i = 1; i <= max; i++) {
  document.write("*".repeat(i) + "<br/>");
}

for (let i = max - 1; i >= 1; i--) {
  document.write("*".repeat(i) + "<br/>");
}

For fun i added a slowly growing example

let max = 1;

setInterval(() => {
  document.body.textContent = "";

  for (let i = 1; i <= max; i++) {
    document.write("*".repeat(i) + "<br/>");
  }

  for (let i = max - 1; i >= 1; i--) {
    document.write("*".repeat(i) + "<br/>");
  }
  
  max++;
}, 500)
Reyno
  • 3,546
  • 10
  • 21
1

Some notes on your code:

  • You should avoid document.write
  • Instead of having nested loops you could use String#repeat, to replicate the * character.
  • To manage the descend you just have to check whether the index has surpassed the half way point, and if it has print totalHeight - index + 1 amount of *;

Here is a interactive example based on the above notes.

function printTree(size, dom) {
  if (!(dom instanceof HTMLElement)) dom = document.body; // if the element hasn't been defined get the body element
  dom.innerHTML = ""; // clear any old content of the element
  var half = Math.ceil(size / 2); // get the halfway point to compare (and avoid extra calculations inside loop);
  for (var index = 1; index <= size; index++) {
    dom.appendChild(document.createElement("div")).textContent = "*".repeat(index > half ? size - index + 1 : index);
  }
}

var input = document.querySelector("#num"),
  content = document.querySelector("#content");
input.addEventListener("input", refresh);
refresh();

function refresh() {
  printTree(+input.value, content);
}
<input type="number" id="num" value="5" />
<div id="content"></div>
nick zoum
  • 6,639
  • 5
  • 26
  • 63