ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Simple Array Summation

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1/**
2* Calculates the sum of all numbers in an array.
3* @param {number[]} arr - The input array of numbers.
4* @returns {number} The sum of the numbers in the array.
5*/
6function sumArray(arr) {
7// Initialize accumulator to 0. This handles the case of an empty array correctly.
8let sum = 0;
9
10// Check if the input is actually an array and not null/undefined.
11if (!Array.isArray(arr)) {
12console.error("Input must be an array.");
13return 0; // Or throw an error, depending on desired behavior.
14}
15
16// Iterate through each element of the array.
17// The loop starts at index 0 and continues as long as i is less than the array length.
18for (let i = 0; i < arr.length; i++) {
19// Add the current element to the sum.
20// Ensure the element is a number before adding.
21if (typeof arr[i] === 'number') {
22sum += arr[i];
23} else {
24console.warn(`Element at index ${i} is not a number and will be skipped:`, arr[i]);
25}
26}
27
28// Return the final calculated sum.
29return sum;
30}
31
32// Example Usage:
33// const numbers1 = [1, 2, 3, 4, 5];
34// console.log(`Sum of [${numbers1}]:`, sumArray(numbers1)); // Output: 15
35
36// const numbers2 = [-1, -2, 3, 4, -5];
37// console.log(`Sum of [${numbers2}]:`, sumArray(numbers2)); // Output: -1
38
39// const emptyArray = [];
40// console.log(`Sum of [${emptyArray}]:`, sumArray(emptyArray)); // Output: 0
41
42// const mixedArray = [1, 'a', 3, null, 5];
43// console.log(`Sum of [${mixedArray}]:`, sumArray(mixedArray)); // Output: 9 (with warnings)
44
45// const invalidInput = null;
46// console.log(`Sum of ${invalidInput}:`, sumArray(invalidInput)); // Output: 0 (with error)
Algorithm description viewbox

Simple Array Summation

Algorithm description:

This scenario involves implementing a basic array summation function. The goal is to correctly calculate the sum of all numeric elements within a given array. It emphasizes handling edge cases such as empty arrays, arrays containing non-numeric values, and invalid input types, ensuring the function is robust and predictable.

Algorithm explanation:

The `sumArray` function initializes a `sum` variable to 0. It first checks if the input `arr` is a valid array. If not, it logs an error and returns 0. It then iterates through the array using a `for` loop, from index 0 up to (but not including) `arr.length`. Inside the loop, it checks if the current element `arr[i]` is a number. If it is, the element is added to `sum`. If not, a warning is logged, and the element is skipped. This ensures that only numeric values contribute to the sum. The loop boundaries are correctly set to include all elements. The initial value of `sum = 0` correctly handles empty arrays, returning 0. Time complexity is O(N) because each element in the array is visited once. Space complexity is O(1) as only a few variables are used regardless of the input array size.

Pseudocode:

Function `sumArray(arr)`:
  Initialize `sum` to 0.
  If `arr` is not an array:
    Log error.
    Return 0.
  For each `element` in `arr` at index `i`:
    If `element` is a number:
      Add `element` to `sum`.
    Else:
      Log warning.
  Return `sum`.