# Calculate Sum of the Elements of the Array

Problem Statement: Given an array, we have to find the sum of all the elements in the array.

Examples:

```Example 1:
Input: N = 5, array[] = {1,2,3,4,5}
Output: 15
Explanation: Sum of all the elements is 1+2+3+4+5 = 15

Example 2:
Input:  N=6, array[] = {1,2,1,1,5,1}
Output: 11
Explanation: Sum of all the elements is 1+2+1+1+5+1 = 11```

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Solution 1: Using for loop

Approach

• Using for loop traverse through the array and while traversing  maintain  a variable for storing sum of the elements in the array.
• After completing the traversal simply print the sum. Code:

## C++ Code

``````#include<bits/stdc++.h>
using namespace std;
int main() {
int n = 5;
vector<int>arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < n; i++) {
sum += (double)arr[i];
}
cout <<"The sum of the elements of the array is "<< sum;
}
``````

Output:

The sum of the elements of the array is 15

Time Complexity: O(n) As we traverse the array once.

Space Complexity: O(1).

## Java Code

``````import java.util.*;
public class Main {
public static void main(String args[]) {
int n = 5;
int arr[] = {1,2,3,4,5};
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
System.out.println("The sum of the elements of the array is "+sum);
}
}
``````

Output:

The sum of the elements of the array is 15

Time Complexity: O(n) As we traverse the array once.

Space Complexity: O(1).

Solution 2: Using collection in Java or STL in C++

Approach:

For C++: “accumulate” is used to calculate the sum of all the elements in the array.

For Java: Instream sum() gives the sum of all the elements in the stream.

Code:

## C++ Code

``````#include<bits/stdc++.h>
using namespace std;
int main() {

int n = 5;
int arr[] = {1, 2, 3, 4, 5};
int initialSum = 0;
cout <<"The sum of the elements of the array is ";
cout<<accumulate(arr, arr + n, initialSum);

}``````

Output:

The sum of the elements of the array is 15

Time Complexity: O(n).

Space Complexity: O(1).

## Java Code

``````import java.util.*;
import java.util.stream.IntStream;
public class Main {
public static void main(String args[]) {
int n = 5;
int arr[] = {1,2,3,4,5};
int sum = IntStream.of(arr).sum();
System.out.println("The sum of the elements of the array is "+sum);
}
}
``````

Output:

The sum of the elements of the array is 15

Time Complexity: O(n).

Space Complexity: O(1).

Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article