Program to find sum of elements in a given array

21 Jun, 2022
Given an array of integers, find sum of its elements.Examples : 
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50
C++
C
Java
Python3
C#
PHP
Javascript
/* 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 codeint 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
/* 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 nint 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;}
/* 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 arraydef _sum(arr,n):          # return sum using sum     # inbuilt sum() function    return(sum(arr))  # driver functionarr=[]# input values to listarr = [12, 3, 4, 15]  # calculating length of arrayn = len(arr)  ans = _sum(arr,n)  # display sumprint ('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.
<?php// PHP Program to find sum of // elements in a given array   // function to return sum // of elements in an array// of size nfunction 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?>
<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>
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
Another Method: Using STLCalling inbuilt function for sum of elements of an array in STL.accumulate(first, last, sum);first, last : first and last elements of range                  whose elements are to be addedsum :  initial value of the sum
This function returns the array sum.
C++
Java
Python3
C#
Javascript
/* C++ Program to find sum of elements in a given array */#include <bits/stdc++.h>using namespace std;  // Driver codeint 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
/* Java Program to find sum of elements in a given array */import java.util.*;  class GFG{      static int accumulate(int []arr)        {            int sum = 0;            for(int i = 0; i < arr.length; i++)            {                sum = sum + arr[i];            }            return sum;        }       // Driver codepublic static void main(String[] args) {     int arr[] = {12, 3, 4, 15};     int n = arr.length;           // calling accumulate function, passing first, last element and    // initial sum, which is 0 in this case.    System.out.print("Sum of given array is " +  accumulate(arr)); } }   // This code is contributed by umadevi9616
# Python3 program to find sum of elements # in a given array   # Driver codeif __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;public class GFG {      static int accumulate(int[] arr) {        int sum = 0;        for (int i = 0; i < arr.Length; i++) {            sum = sum + arr[i];        }        return sum;    }      // Driver code    public static void Main(String[] args)     {        int []arr = { 12, 3, 4, 15 };        int n = arr.Length;          // calling accumulate function, passing first, last element and        // initial sum, which is 0 in this case.        Console.Write("Sum of given array is " + accumulate(arr));    }}  // This code is contributed by gauravrajput1 
<script>     /* javascript Program to find sum of elements    in a given array */          function accumulate(arr)    {        let sum = 0;        for(let i = 0; i < arr.length; i++)        {            sum = sum + arr[i];        }        return sum;    }      // Driver code      let arr = [12, 3, 4, 15];    let n = arr.length;          // calling accumulate function, passing first, last element and    // initial sum, which is 0 in this case    document.write("Sum of given array is " + accumulate(arr));          // This code is contributed by vaibhavrabadiya3.</script>
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
Find sum of elements in a given array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind sum of elements in a given array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=sKHKHrEfHbI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Another Method#2: Using Recursion
C++
/* C++ Program to find sum of elementsin a given array using recursion */#include<iostream>using namespace std;  // function to return sum of elements// in an array of size nint 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;    // This code is contributed by Shivesh Kumar Dwivedi}
34
jit_t
rathbhupendra
surbhityagi15
rishavmahato348
pranoy_coder
ukasp
vaibhavrabadiya3
umadevi9616
GauravRajput1
anandkumarshivam2266
cpdwivedi916
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.