DEV Community

NdegwaJulius
NdegwaJulius

Posted on

HackerRank Series #1: Simple Array Sum

Problem Statement
Given an array of integers, find the sum of its elements.

For example, if the array $ar = [1,2,3], 1+2+3 =6, so return 6.

Function Description
Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

simpleArraySum has the following parameter(s):

ar: an array of integers
Sample Input : 1 2 3 4 10 11
Sample Output : 31

Explanation
In our text editor on HackerRank, we already have the simpleArraySum() function declared with the parameter $ar which can be any given array. All you need to do is write a set of instructions in the function that will calculate the sum of all array elements so whenever the function is called, it can calculate the sum of the array elements of any simple array.
For example in our Sample Input [1, 2, 3, 4, 10, 11], we expect an output of 31 seeing 1 +2+ 3+ 4 +10 +11 = 31.

Solution
A loop will work fine!

Psuedocodes
Let's try to solve this problem without using codes.

Initialize sum to 0.
Loop through the array and get the array elements and add the value to sum.
At each loop sum is updated with the latest sum value after the previous array element has been added.
After the loop, return sum.
Now, let's go coding!

I will be using the for method in Javascript through the array and solve this problem.
Now, we can write the Javascript code as follows:

function simpleArraySum(ar) {

   let sum=0;
   for( let i=0;  i<ar.length;  i++ ){
       sum+=ar[i];
   }
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion
This would return an output of the sum of the array as a single integer. When using the for method, we are fetching the array elements based on their index so be careful not to do i<=ar.length; in your condition statement. Avoid this common error because an array starts at index [0].

Congratulations!🎉🎈 You completed your first warmup challenge on HackerRank.

Top comments (0)