javascripthtmlalgorithmtriangulartriangle

Triangle with an empty center based on a given height in Javascript


I had a task recently to do an empty triangle based on a random height given by a user.

It had to look like that but the user set the height

It had to look like that but the user was the one who could set the height.
My script looks like this now:

var hgh = prompt("Set the triangle's height: ");

  document.write("<center><pre>");
  for (var i = 1; i <= hgh ; i++) {
    var s = "";
    for (var j = 1; j <= (2 * hgh - 1); j++) {
      if (i != hgh ) {
        if (j == hgh + 1 - i || j == hgh - 1 + i) {
           s += "X";
        }
        else {
          s += " ";
        }
      }
      else {
        s += "X";
      }
    }
    document.write(s);
    document.write("<br>");
  }
  document.write("</pre></center>");

The result looks like this:

Which part of my script do I have to correct so that it displays the triangle correctly?


Solution

  • The problem is in this condition:

    if (j == hgh + 1 - i ... )
    

    hgh is in reality a string (because prompt returns a string). So the "+" operator works on strings here and concatenates hgh and "1" instead of adding these values. If you enter "5", (hgh + 1) will result in "51", not "6".

    Quick solution: Rewrite the expression as hgh - i + 1. There is no string subtraction, so (hgh - i) will convert hgh into a number and do a proper subtraction.