Tutorialspoint
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.
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.
Constraints
  • 0 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysNumberAccentureeBay
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Check if the array is empty and return 0 if true
 Step 2: Initialize a sum variable to 0 to store the running total
 Step 3: Create a loop that iterates from index 0 to array length - 1
 Step 4: In each iteration, add the current array element to the sum variable
 Step 5: Continue the loop until all elements have been processed
 Step 6: Return the final sum value after loop completion
 Step 7: Test with various arrays including empty, single element, and mixed positive/negative numbers

Submitted Code :