🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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:
15Input:
[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.accis the accumulator (the running total).curris the current element being processed.0is 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment