Open In App

Program to find sum of elements in a given array

Last Updated : 20 Sep, 2024
Comments
Improve
Suggest changes
101 Likes
Like
Report

Given an array of integers, find the sum of its elements.

Examples:

Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

Sum of elements of an array using Recursion:

The idea is to use recursive approach which calculates the sum of an array by breaking it down into two cases: the base case, where if the array is empty the sum is 0; and the recursive case, where the sum is calculated by adding the first element to the sum of the remaining elements which is computed through a recursive call with the array shifted by one position and size reduced by one.

Below is the implementation of the above approach:

C++
C Java Python C# JavaScript

Output
34

Time Complexity: O(n)
Auxiliary Space: O(n), Recursive stack space

Sum of elements of an array using Iteration:

The idea is to iterate through each element of the array and adding it to a variable called sum. The sum variable is initialized to 0 before the iteration starts. After the iteration, the final sum is returned.

Below is the implementation of the above approach:

C
C++ Java Python C# JavaScript PHP

Output
Sum of given array is 34

Time Complexity: O(n)
Auxiliary Space: O(1)

Sum of elements of an array using Inbuild Methods:

The idea is to make use of built-in functions to find the sum of elements in a given array. These functions eliminate the need for explicit iteration, enhancing code simplicity.

Below is the implementation of above approach:

C++
Java Python C# JavaScript

Output
Sum of given array is 34

Time Complexity: O(n)
Auxiliary Space: O(1)


Next Article

Similar Reads