JavaScript Algorithm: Simple Array Sum

0 19
Avatar for buzz.lightyear
3 years ago

On the algorithm, Simple Array Sum, you are given an array of integers and you are to find the sum of its elements.

The input of the function simpleArraySum, you are given an array. You can think of an array like a train:

You can think of a train being an array and each railroad car contains an item. That item can be a string, numbers, or another array. Because we are trying to find the sum of something, the items in the array will be a number. For this example, the array will contain four numbers.

Before we do something to the array, you’ll need a variable to hold the sum. We can name the variable total. A way to begin this is to assign the first item in the array to the variable. Computers start counting at zero so to get the first item of an array, you write total[0]. Zero is the first item.

Now to loop through the array, we will use a for-loop. A for-loop loops through an item under certain conditions. Since our total variable has already counted the first item on the array, you start counting at the second item or [1]. Then you allow the for-loop to increment through the array up until the last item(the numbers have to be less than the length of the array and not less than and equal to). Remember computers start counting at zero, there is no fifth item.

In this function, you don’t know the length of the array so using the .length property will help you find the length of the array without you hardcoding the length. The length can be three items, four items, or ten items long. The length method will count the number of items in an array and return the number.

Going back to the train analogy, think of a for-loop as the train going through a tunnel. Each railroad car will enter the tunnel one at a time and each number inside the railroad car is tossed (or added) into the total variable:

Because the total variable already started with a value of 1 (the first array item was added into the variable before the loop) and the second value of the array is 2, the total is now 3.

This continues until the entire array goes through the for-loop:

Now that the for-loop has looped through the entire array, all of the values when added or 1+2+3+4 will total to 10.

Our total variable inside our simpleArraySum function will return 10.

Originally written (by me) on Medium. All illustrations were made by the writer of this article.

1
$ 0.00
Avatar for buzz.lightyear
3 years ago

Comments