Problem Statement

You’re given an array of numbers, and you need to calculate and print the sum of all elements in the given array.

Example 1: Let arr = [1, 2, 3, 4, 5]

Therefore, the sum of all elements of the array = 1 + 2 + 3 + 4 + 5 = 15.

Thus, the output is 15.

Example 2: Let arr = [34, 56, 10, -2, 5, 99]

Therefore, the sum of all elements of the array = 34 + 56 + 10 + (-2) + 5 + 99 = 202.

Thus, the output is 202.

Approach to Find the Sum of All Elements in an Array

You can find the sum of all elements in an array by following the approach below:

Initialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.

C++ Program to Find the Sum of All Elements in an Array

Below is the C++ program to find the sum of all elements in an array:

Output:

C++ Program Using STL to Find the Sum of All Elements in an Array

You can also use C++ STL to find the sum of all elements in an array.

Output:

Python Program to Find the Sum of All Elements in an Array

Below is the Python program to find the sum of all elements in an array:

Output:

Python Program Using Built-in Function to Find the Sum of All Elements in an Array

You can also use Python’s sum() function to find the sum of all elements in an array.

Output:

JavaScript Program to Find the Sum of All Elements in an Array

Below is the JavaScript program to find the sum of all elements in an array:

Output:

JavaScript Program Using the reduce() Method to Find the Sum of All Elements in an Array

You can also use JavaScript’s reduce() method to find the sum of all elements in an array.

Output:

Want to Learn C++?

C++ is among the most popular programming languages. You can use C++ for basic programming, developing games, developing GUI-based applications, developing database software, developing operating systems, and much more.

If you’re a beginner to C++ or want to revise your C++ concepts, check out some of the top websites and courses to get you started.