My script can print a pattern of triangular numbers (e.g. 1, 3, 6, 10,...), but I want to store the formula (n * (n + 1)) / 2
in a variable called formula
instead of writing it multiple times in the if-else statement.
/* Current script */
var pat = document.getElementById("pattern");
var nMax = 10; // max number of intervals
for (var n = 1; n <= nMax; ++n) {
if (n != nMax)
// insert comma and space after each interval
pat.innerHTML += (n * (n + 1)) / 2 + ", ";
else
// append ellipsis after last interval
pat.innerHTML += (n * (n + 1)) / 2 + ",…";
}
<body>
<p id="pattern"></p>
</body>
Here is what I tried already but ended up with 1, 1, 1, 1, 1...:
I moved var n = 1
to its own line under the nMax
variable so that n
is defined in the formula and changed the first part of the for
loop to n = 1
. Then in the if-else statement, I replaced every instance of (n * (n + 1)) / 2
with the formula
variable. After testing the modified script, the pattern resulted in all 1s.
/* Version with formula variable (not working properly) */
var pat = document.getElementById("pattern");
var nMax = 10; // max number of intervals
var n = 1;
var formula = (n * (n + 1)) / 2;
for (n = 1; n <= nMax; ++n) {
if (n != nMax)
// insert comma and space after each interval
pat.innerHTML += formula + ", ";
else
// append ellipsis after last interval
pat.innerHTML += formula + ",…";
}
<body>
<p id="pattern"></p>
</body>
How could I store the formula in a variable and use it without getting unexpected results?
Put the formula in a function:
function formula(n) { return n * (n + 1) / 2; }
Then you can call it :
pat.innerHTML = formula(n) + ", ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With