Open In App

Program to find sum of elements in a given array

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++ Program to find sum of elements
in a given array using recursion */
#include <iostream>
using namespace std;

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    // base case
    if (n == 0) {
        return 0;
    }
    else {
        // recursively calling the function
        return arr[0] + sum(arr + 1, n - 1);
    }
}
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << sum(arr, n);
    return 0;
  
}
/* C++ Program to find sum of elements
in a given array using recursion */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    // base case
    if (n == 0) {
        return 0;
    }
    else {
        // recursively calling the function
        return arr[0] + sum(arr + 1, n - 1);
    }
}

int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%d", sum(arr, n));

    return 0;
}
/*package whatever //do not write package name here */
import java.io.*;
class GFG {

    static int sum(int[] arr, int n)
    {

        // base or terminating condition
        if (n <= 0) {
            return 0;
        }

        // Calling method recursively
        return sum(arr, n - 1) + arr[n - 1];
    }

    public static void main(String[] args)
    {

        int arr[] = { 12, 3, 4, 15 };
        int s = sum(arr, arr.length);

        System.out.println(s);
    }
}
# python Program to find sum of elements
# in a given array using recursion

# function to return sum of elements
# in an array of size n


def sum1(arr):
    if len(arr) == 1:
        return arr[0]
    else:
        return arr[0] + sum1(arr[1:])


arr = [12, 3, 4, 15]
print(sum1(arr))

# This code is contributed by laxmigangarajula03
using System;

public class GFG {

    static int sum(int[] arr, int n)
    {
        // base or terminating condition
        if (n <= 0) {
            return 0;
        }

        // Calling method recursively
        return sum(arr, n - 1) + arr[n - 1];
    }

    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int s = sum(arr, arr.Length);

        Console.Write(s);
    }
}

// This code is contributed by ksrikanth0498.
function sum(let arr, let n)
  {
    // base or terminating condition
    if (n <= 0) {
      return 0;
    }

    // Calling method recursively
    return sum(arr, n-1 ) + arr[n-1];
  }



    let arr = {12, 3, 4, 15};
    let s = sum(arr, arr.length);

    document.write(s);

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 Program to find sum of elements
 in a given array */
#include <bits/stdc++.h>

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    int sum = 0; // initialize sum

    // Iterate through all elements
    // and add them to sum
    for (int i = 0; i < n; i++)
        sum += arr[i];

    return sum;
}

int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Sum of given array is %d", sum(arr, n));
    return 0;
}
/* C++ Program to find sum of elements
in a given array */
#include <bits/stdc++.h>
using namespace std;

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    int sum = 0; // initialize sum

    // Iterate through all elements
    // and add them to sum
    for (int i = 0; i < n; i++)
        sum += arr[i];

    return sum;
}

// Driver code
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Sum of given array is " << sum(arr, n);
    return 0;
}

// This code is contributed by rathbhupendra
/* Java Program to find sum of elements in a given array  */
class Test {
    static int arr[] = { 12, 3, 4, 15 };

    // method for sum of elements in an array
    static int sum()
    {
        int sum = 0; // initialize sum
        int i;

        // Iterate through all elements and add them to sum
        for (i = 0; i < arr.length; i++)
            sum += arr[i];

        return sum;
    }

    // Driver method
    public static void main(String[] args)
    {
        System.out.println("Sum of given array is "
                           + sum());
    }
}
# Python 3 code to find sum
# of elements in given array


def _sum(arr, n):

    # return sum using sum
    # inbuilt sum() function
    return(sum(arr))


# driver function
arr = []
# input values to list
arr = [12, 3, 4, 15]

# calculating length of array
n = len(arr)

ans = _sum(arr, n)

# display sum
print('Sum of the array is ', ans)

# This code is contributed by Himanshu Ranjan
// C# Program to find sum of elements in a
// given array
using System;

class GFG {

    // method for sum of elements in an array
    static int sum(int[] arr, int n)
    {

        int sum = 0; // initialize sum

        // Iterate through all elements and
        // add them to sum
        for (int i = 0; i < n; i++)
            sum += arr[i];

        return sum;
    }

    // Driver method
    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int n = arr.Length;

        Console.Write("Sum of given array is "
                      + sum(arr, n));
    }
}

// This code is contributed by Sam007.
<script>
//JavaScript Program to find 
//sum of elements in a given array 

    // function to return sum of elements  
    // in an array of size n  
    function sum(arr) {  
        let sum = 0; // initialize sum  
  
        // Iterate through all elements  
        // and add them to sum  
        for (let i = 0; i < arr.length; i++)  
            sum += arr[i];  
  
        return sum;  
    }  
    
    // Driver code 
    let arr = [12, 3, 4, 15];
    document.write("Sum of given array is " + sum(arr));
    
 // This code is contributed by Surbhi Tyagi  
</script>
<?php
// PHP Program to find sum of 
// elements in a given array 

// function to return sum 
// of elements in an array
// of size n
function sum( $arr, $n)
{
    // initialize sum
    $sum = 0; 

    // Iterate through all elements 
    // and add them to sum
    for ($i = 0; $i < $n; $i++)
    $sum += $arr[$i];

    return $sum;
}

// Driver Code
$arr =array(12, 3, 4, 15);
$n = sizeof($arr);
echo "Sum of given array is ", 
                sum($arr, $n);

// This code is contributed by aj_36
?>

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++ Program to find sum of elements
in a given array */
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // calling accumulate function, passing first, last
    // element and
    // initial sum, which is 0 in this case.
    cout << "Sum of given array is "
         << accumulate(arr, arr + n, 0);
    return 0;
}

// This code is contributed by pranoy_coder
import java.util.Arrays;

public class GFG {
    // Driver code
    public static void main(String[] args) {
        int[] arr = {12, 3, 4, 15};
        int sum = Arrays.stream(arr).sum();
        System.out.println("Sum of given array is " + sum);
    }
}
# Python3 program to find sum of elements
# in a given array

# Driver code
if __name__ == "__main__":

    arr = [12, 3, 4, 15]
    n = len(arr)

    # Calling accumulate function, passing
    # first, last element and initial sum,
    # which is 0 in this case.
    print("Sum of given array is ", sum(arr))

# This code is contributed by ukasp
// C# Program to find sum of elements in a
// given array
using System;
using System.Linq;

class GFG {

    // Driver method
    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int n = arr.Length;

        // calling LINQ Sum method on the array
        // to calculate the sum of elements in an array
        int sum = arr.Sum();

        Console.Write("Sum of given array is " + sum);
    }
}

// This code is contributed by abhishekmaran_.
// JavaScript program to find the sum of elements
// in a given array

// Driver code
const arr = [12, 3, 4, 15];
const n = arr.length;

// Calling the built-in reduce function to calculate the sum of elements in the array.
const sumOfArray = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log("Sum of given array is ", sumOfArray);

// This code is contributed by Yash Agarwal(yashagarwal2852002)

Output
Sum of given array is 34




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

Sum of elements of an array using Divide and Conquer:

The idea behind this approach is to utilize the divide and conquer strategy to find the sum of elements in a given array. This method involves three steps: Divide, Conquer and Combine.

1. Divide: Divide the array into smaller subarrays until each subarray has only one element.

2. Conquer: Calculate the sum of elements in each subarray. If the array contains only one element, return that element as the sum.

3. Combine: Combine the sums of subarrays to obtain the final sum of the entire array.

Below is the implementation of the above approach:

#include <iostream>
#include <vector>
using namespace std;

// Function to find the sum of elements in an array using divide and conquer
int sum(vector<int>& arr, int low, int high) {
    // Base case: If the array contains only one element
    if (low == high) {
        return arr[low];
    } 
    else {
        int mid = (low + high) / 2;
        // Divide the array into two halves and recursively calculate the sum
        int left_sum = sum(arr, low, mid);
        int right_sum = sum(arr, mid + 1, high);
        // Combine the sums of the subarrays
        return left_sum + right_sum;
    }
}

int main() {
    vector<int> arr = {12, 3, 4, 15};
    int n = arr.size();
    cout << "Sum of given array is " << sum(arr, 0, n - 1);
    return 0;
}
// Nikunj Sonigara

Output
Sum of given array is 34

Time Complexity: O(n log n)

Space Complexity: O(log n)

Article Tags :