leo nasution leo nasution - 7 months ago 11
Javascript Question

how to make triangle with ordered number



i am making code for java to make triangle ordered number just like this

1

2 3

4 5 6

7 8 9 10

which is using for loops. and i just allowed to input the row only.

if i input 3 and there will be

1

2 3

4 5 6

how i can do that? please



var rows= prompt("Jumlah baris");
var color= prompt("color1:");
var color1 = prompt("color2:");
var d = 1;
var bas = parseInt(rows);
document.write("<table align=center width=500 height=500 border=2>");
for (i = 1; i <= rows; i++) {
document.write("<tr>");
for (l = 1; l <= i; l++) {
if ((i + l) % 2 === 1) {
document.write("<td bgcolor=" + color + ">" + d + "</td>");
d++;
} else {
document.write("<td bgcolor=" + color1 + ">" + d + "</td>");
d++;
}
}
document.write("</tr>");
}
document.write("</table>");
</script>

Answer

Very simple, really - instead of using a variable inside like you have done, use a variable with a value that goes on increasing.

<script type="text/javascript">
    var rows= prompt("input");
    var t = 1;
    for (i = 1; i <= rows; i++) {

        for (l = 1; l <= i; l++) {
            document.write(t + ' ');
            t++;
        }
        document.writeln(" <br/>");
    }
</script>

t will go on increasing as we never reset it; it increases alongwith l, but never resets.