0

You are given an array of numbers called numbers. Calculate the sum of numbers and return it from the function. If the next number is equal to 0, the program must stop processing the numbers and return the result.

Sample Input 1:**

11 12 15 10 0 100

Sample Output 1:

48

Sample Input 2:

100 0 100

Sample Output 2:

100

I can't get it to work, this is what I've done so far...

Should I create a counter that will sum up every time it goes in the loop (to check if it's a 0) and another one that gets the 'n' value and sums it up the numbers?

function sum(numbers) {
    let add = 0;

    for (let n in numbers) {
        if (numbers[n] === 0) {
            break;
        }
        if (numbers[n] !== 0) {
            add = numbers[n] + n;
            n++;
        }
        return (numbers[n]);
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
ankkara
  • 3
  • 2
  • `for/in` loops are for iterating over objects. A traditional `for` loop that has a counter or the `Array.forEach()` is for arrays. Also, instead of two, separate `if` statements, you just need one that tests for `0` and breaks if that is the case. If it's not, the code just continues - - no additional `if` needed. Finally, the `return` shouldn't be in the loop. It should happen after the loop has finished. – Scott Marcus Sep 27 '20 at 15:59
  • Re Scott's point about `for-in`, [here are your various options for looping through arrays properly](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476). – T.J. Crowder Sep 27 '20 at 16:03

3 Answers3

0

for/in loops are for iterating over objects. A traditional for loop that has a counter or the Array.forEach() is for arrays. (Thanks to @T.J. Crowder for the link) Also, instead of two, separate if statements, you just need one that tests for 0 and breaks if that is the case. If it's not, the code just continues - - no additional if needed. Finally, the return shouldn't be in the loop. It should happen after the loop has finished.

function sum(numbers) {
    let add = 0;

    // Array.reduce() is really the best solution here, 
    // but not what your assignment wants you to use.
    // for/in is really for iterating over objects, 
    // while a counting `for` loop is for arrays
    for (var i = 0; i < numbers.length; i++) {
        if (numbers[i] === 0) {
            break;
        }
        
        // No need for another "if". If the code has
        // reached this point, the current array number
        // must not be zero, so just add it to the 
        // overall accumulator variable
        add += numbers[i];
    }
    
    return add;  // After iterating the loop, return the accumulator
}

console.log(sum([11, 12, 15, 10, 0, 100]));
console.log(sum([100, 0, 100]));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Please use let instead of var in the for loop as var is bad practice especially here as the counter is not needed outside the loop. – andrbrue Sep 27 '20 at 16:11
  • @andrbrue `var` is not *very bad practice*. `let` is certainly good and helps with closure issues, but `var` is not a red-headed step-child and perfectly valid code. – Scott Marcus Sep 27 '20 at 16:12
  • Counter variables are nothing you want to have in the scope of the complete function. Using var just is prone to mistakes afterwards if for instance i would be redeclared. This could become confusing for a beginner especially. Also mind that Jetbrains IDEs even add warnings to each var, ankkara is following one of their guides. – andrbrue Sep 27 '20 at 16:17
  • Thank you very much Scott and Andrbrue not for the answer but especially for the explanations you have give in detail. I think my problem was that I overthinked about the array indexes and elements and the loops. I'm new at programming and I appreciate a lot the help. Thank you very much :) – ankkara Sep 27 '20 at 16:23
  • @ankkara `var` is no more prone to misuse as `let` or `const` are. This is an example that does not center around the scope of the loop variable and so, it's irrelevant. But, your point really isn't valid. Using the proper scope for your current needs is really the point. That could mean `let` or `var`. Neither is inherently "good" or "bad". – Scott Marcus Sep 27 '20 at 18:38
0

I can see multiple problems with your current code. First of all you should name the function in a better way that describes what it actually does. Your for loop does not make sense as with n in numbers you get the elements and not the indexes, so numbers[n] does not make sense. The let in the loop instruction should not be there. The second if block could be an else. add should be set to add + n, the n++ does not make sense. The return should be outside the loop and actually return add.

It looks like you do not have much experience with how a general program flow looks like, so I would recommend to have a look at the single instructions again. If you know their meaning try to do your algorithm on paper step by step to understand what it actually does vs what it should. You could also add some console.log(...) if you have difficulties understanding the current program flow.

andrbrue
  • 721
  • 6
  • 15
0

Here is another problem this time I solved thanks to the explanations, similar to the one above in case it can help anyone:

Find the first occurrence of the number 5 in the given array and return its index. If the number is not found, return -1.

Sample Input 1:

10 3 8 5 3 4 5

Sample Output 1:

3

Sample Input 2:

5 10 111 12

Sample Output 2:

0

 function find5(numbers) {
    let find = 5;
    for (let v = 0; v < numbers.length; v++) {
        if (numbers[v] !== find) {
            continue;
        }
        return (v);
    }
    return(-1);
}

console.log(find5([10, 3, 8, 5, 3, 4, 5]));
console.log(find5([3, 4, 1]));
ankkara
  • 3
  • 2
  • While this exercise does give you the opportunity to use `continue`, remember that the natural "flow" of a program is to continue, so really the better logic would be to introduce conditional code for what that natural flow should be averted (`break`, `return`). You'll find that you won't code yourself into circular logic this way. – Scott Marcus Sep 27 '20 at 18:36
  • Okey, I get your point, continue then It can be "useless" as the code will continue anyways. Thanks, I will keep that in mind! – ankkara Sep 27 '20 at 19:28