0

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
asked Feb 16, 2017 at 6:25
1
  • 1
    What do you mean it isn't working? What is it doing? What is it NOT doing that you want it to? Commented Feb 16, 2017 at 8:01

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

 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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.