JavaScript Algorithm: A Very Big Sum

0 10
Avatar for buzz.lightyear
3 years ago

For today’s algorithm, we will create a function called aVeryBigSum and in this function, it will take in an input that is an array.

When given the array, you calculate and print the sum of the elements in an array. *Note that some of the integers in the array may be quite large.

To start off, we create a variable to hold the sum. This will be the value the function will return. We can call it totalSum.

let totalSum = 0;

You have the array, so it is time to use a for loop to loop through the array:

for (let i = 0; i < ar.length; i++) {
totalSum += ar[i];
}

To look closely at what is going on inside the loop,

totalSum += ar[i];

What this statement means is since totalSum started out with a value of zero, for every item in the array, add it to the total of totalSum.

If the example array is [1, 2, 4, 5]. The function will add the first item in the array, 1, into totalSum (1+0). The next item in the array, 2, will get added into the totalSum variable (1+2) and the value is now 3. And the next will be 3+4 = 7. And after adding the final value, 7 + 5 = 12. the variable totalSum will result in 12.

That is what is going on with that statement. The += is a short way of writing:

totalSum = totalSum + a[i];

After the loop ends, you return the totalSum variable.

return totalSum;

Here is the rest of the function:

function aVeryBigSum(ar) {
    let totalSum = 0;
    for (let i = 0; i < ar.length; i++) {
        totalSum += ar[i];
    }    return totalSum;}

Thank you for reading. To get more JavaScript algorithm solutions, feel free to subscribe.

0
$ 0.00

Comments