'Can someone help me fix the bottom two rows of my nested loop? They shouldn't be the same lengths, but they are

I'm working on a project where I'd like to create the following pattern:

X
XX
XXX
XXXX

.. and so forth. There are twenty rows in all, and the twentieth row should have 20 X's. Here is what I came up with that's so close:

<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="xloop();">Accept</button> <br>
<p id="xloops"></p>

<script>
function xloop() {
let text = "";
for (j=2; j<=20; j++) {
text+= ("X") + ("<br>");
for (k=1; k<j; k++) {
text += ("X");
}
}
document.getElementById("xloops").innerHTML = text;
}
</script>
</body>
</html>

The pattern begins appropriately and does what I want until the very last row. The 20th row only has 19 elements in it, rather than the necessary 20. I have a feeling that this has to do with the "j<k" piece in the k loop being strictly less than j when j equals 20, but any other trial and error combination of indices or inequalities hasn't worked.. is there a way I can remedy this situation using this kind of solution alone without any added complexity?



Solution 1:[1]

I think the following will help you:

<!DOCTYPE html>
<html>
<body>
    <button type="button" onclick="xloop()">Accept</button> <br>
    <p id="xloops"></p>
    <script>
        function xloop() {
            let text = "";
            for (let j = 0; j < 20; j++) {
                let text2 = "";
                for (let k = 0; k <= j; k++) {
                    //row
                    text2 += "X"; 
                }
                //line
                text += `${text2}` + "<br>"
            }
            document.getElementById("xloops").innerHTML = text;
        }
    </script>
</body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S.B