w3resource

JavaScript: Compute the sum of an array of integers

JavaScript Function: Exercise-4 with Solution

Write a JavaScript program to compute the sum of an array of integers.

Example : var array = [1, 2, 3, 4, 5, 6]
Expected Output : 21

Visual Presentation:

JavaScript: Compute the sum of an array of integers

Sample Solution-1:

JavaScript Code:

// Function to calculate the sum of elements in an array using recursion.
var array_sum = function(my_array) {
  // Base case: if the array has only one element, return that element.
  if (my_array.length === 1) {
    return my_array[0];
  }
  else {
    // Recursive case: pop the last element and add it to the sum of the remaining elements.
    return my_array.pop() + array_sum(my_array);
  }
};

// Example usage: Calculate and print the sum of elements in the array [1, 2, 3, 4, 5, 6].
console.log(array_sum([1, 2, 3, 4, 5, 6])); 

Output:

21

Flowchart:

Flowchart: JavaScript recursion function- Compute the sum of an array of integers

Live Demo:

See the Pen javascript-recursion-function-exercise-4 by w3resource (@w3resource) on CodePen.


Sample Solution-2:

JavaScript Code:

// Function to calculate the sum of elements in an array using recursion.
function arraySumRecursive(arr, index = 0) {
  // Base case: if the index exceeds the array length, return 0.
  if (index >= arr.length) {
    return 0;
  } else {
    // Recursive case: add the current element to the sum of the rest of the array.
    return arr[index] + arraySumRecursive(arr, index + 1);
  }
}

// Example usage: Calculate and print the sum of elements in the array [1, 2, 3, 4, 5, 6].
console.log(arraySumRecursive([1, 2, 3, 4, 5, 6])); 

Output:

21

Flowchart:

Flowchart: JavaScript recursion function- Compute the sum of an array of integers

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript program to get the integers in range (x, y).
Next: Write a JavaScript program to compute the exponent of a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-recursion-function-exercise-4.php