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
Ponder: How do we get all the elements of an array๐ค? A loop should 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 inJavascript
andforeach
method inPHP
to loop through the array and solve this problem. This isn't static so you can use any valid method to loop through the array in your preferred language.
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;
}
Now, we can write the PHP
code as follows:
function simpleArraySum($ar) {
$sum=0;
foreach($ar as $value){
$sum+=$value;
}
return $sum;
}
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.
P.S: This is the beginning of a series on the warmup algorithm challenges from HackerRank so stay tuned for more amazing challenges.
Top comments (2)
A implementing Higher Order functions reduce function can make it easier
const arr=[1,2,3,4,5]
console.log(arr.reduce((a,b)=>a+b)) // Outputs: 15
it will solve one test case . But there is another test case which has got arr lenth more than 1000 and for that test case above solution fails .