Introduction
Finding the sum of elements in an array is a common task in programming. JavaScript provides several ways to calculate the sum, including using a loop or the reduce()
method. This program demonstrates how to find the sum of all elements in an array efficiently.
Problem Statement
Create a JavaScript program that:
- Accepts an array of numbers.
- Calculates the sum of all elements in the array.
- Returns and displays the sum.
Example:
Input:
[1, 2, 3, 4, 5]
Output:
15
Input:
[10, 20, 30]
Output:
60
Solution Steps
- Read the Input Array: Provide an array of numbers either as user input or directly within the code.
- Find the Sum: Use the
reduce()
method to accumulate the sum of the array elements. - Display the Result: Print the calculated sum.
JavaScript Program
// JavaScript Program to Find the Sum of Elements in an Array
// Author: https://www.javaguides.net/
function sumOfArray(arr) {
// Step 1: Calculate the sum using the reduce() method
let sum = arr.reduce((acc, curr) => acc + curr, 0);
// Step 2: Return the sum
return sum;
}
// Example input
let array = [1, 2, 3, 4, 5];
let totalSum = sumOfArray(array);
console.log(`The sum of elements in the array is: ${totalSum}`);
Output
The sum of elements in the array is: 15
Example with Different Input
let array = [10, 20, 30];
let totalSum = sumOfArray(array);
console.log(`The sum of elements in the array is: ${totalSum}`);
Output:
The sum of elements in the array is: 60
Explanation
Step 1: Calculate the Sum Using reduce()
- The
reduce()
method iterates over the array, accumulating the sum of its elements.acc
is the accumulator (the running total).curr
is the current element being processed.0
is the initial value for the accumulator.
Step 2: Return and Display the Sum
- The total sum is returned by the function and printed using
console.log()
.
Alternative Method: Using a Loop
You can also calculate the sum using a for
loop:
function sumOfArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
This also produces the same result but is slightly more verbose than using reduce()
.
Conclusion
This JavaScript program demonstrates how to calculate the sum of elements in an array using the reduce()
method. This method is concise and efficient for handling array operations. You can also use a loop for the same task, depending on your preference. This solution is versatile and works with arrays of any size.
Comments
Post a Comment
Leave Comment