
Problem
Solution
Submissions
Sum of Array Elements
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to calculate the sum of all elements in an array of integers. The function should iterate through the array and return the total sum of all elements. Handle edge cases like empty arrays.
Example 1
- Input: arr = [1, 2, 3, 4, 5]
- Output: 15
- Explanation:
- The array [1, 2, 3, 4, 5] is processed element by element.
- Sum = 1 + 2 + 3 + 4 + 5 = 15.
- Therefore, the sum of all elements is 15.
- The array [1, 2, 3, 4, 5] is processed element by element.
Example 2
- Input: arr = [-1, -2, 3, 4]
- Output: 4
- Explanation:
- The array [-1, -2, 3, 4] contains both positive and negative numbers.
- Sum = -1 + (-2) + 3 + 4 = 4.
- Therefore, the sum of all elements is 4.
- The array [-1, -2, 3, 4] contains both positive and negative numbers.
Constraints
- 0 ≤ arr.length ≤ 1000
- -1000 ≤ arr[i] ≤ 1000
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Initialize a sum variable to 0 before starting the iteration
- Use a loop to iterate through each element of the array
- Add each element to the sum variable during iteration
- Handle the edge case of an empty array by returning 0
- Return the final sum after completing the iteration