My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Soubhik Mondal
2,6661 gold badge15 silver badges19 bronze badges
-
1What do you mean it isn't working? What is it doing? What is it NOT doing that you want it to?StudioTime– StudioTime2017年02月16日 08:01:05 +00:00Commented Feb 16, 2017 at 8:01
4 Answers 4
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
answered Feb 16, 2017 at 6:34
Evan Knowles
7,5592 gold badges41 silver badges73 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
answered Feb 16, 2017 at 6:38
Azeez Kallayi
2,6421 gold badge17 silver badges19 bronze badges
Comments
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
answered Feb 16, 2017 at 6:41
Soubhik Mondal
2,6661 gold badge15 silver badges19 bronze badges
Comments
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);
answered Feb 16, 2017 at 6:47
Suhani Mendapara
3071 gold badge3 silver badges10 bronze badges
Comments
lang-js