Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find if sum of elements of given Array is less than or equal to K
Next article icon

Program to find sum of elements in a given array

Last Updated : 20 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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++ 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
/* 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; } 
Java
/*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
# 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 
C#
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. 
JavaScript
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
/* 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++
/* 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
/* 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
# Function to return sum of  # elements in an array def sum_array(arr):     total = 0  # initialize sum          # Iterate through all elements     # and add them to total     for num in arr:         total += num     return total  # Driver code arr = [12, 3, 4, 15] print("Sum of given array is", sum_array(arr)) 
C#
// 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. 
JavaScript
//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];     console.log("Sum of given array is " + sum(arr));       // This code is contributed by Surbhi Tyagi   
PHP
<?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++
/* 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 
Java
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);     } } 
Python
# 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#
// 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
// 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)



Next Article
Find if sum of elements of given Array is less than or equal to K
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Basic Coding Problems
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Program to find sum of elements in a given 2D array
    Given a 2D array of order M * N, the task is to find out the sum of elements of the matrix. Examples: Input: array[2][2] = {{1, 2}, {3, 4}};Output: 10 Input: array[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};Output: 136 Approach: The sum of each element of the 2D array ca
    12 min read
  • Program to print Sum of even and odd elements in an array
    Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
    13 min read
  • Find the sum of all possible pairs in an array of N elements
    Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.Examples: Input: arr[] = {1, 2} Output: 12 All va
    7 min read
  • Find if sum of elements of given Array is less than or equal to K
    Given an array arr[] of size N and an integer K, the task is to find whether the sum of elements of the array is less than or equal to K or not. Examples: Input: arr[] = {1, 2, 8}, K = 5Output: falseExplanation: Sum of the array is 11, which is greater than 5 Input: arr[] = {2}, K = 5Output: true Ap
    3 min read
  • Find sum of non-repeating (distinct) elements in an array
    Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
    14 min read
  • Construct sum-array with sum of elements in given range
    You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = ?arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0. Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {
    7 min read
  • Sum of multiples of Array elements within a given range [L, R]
    Given an array arr[] of positive integers and two integers L and R, the task is to find the sum of all multiples of the array elements in the range [L, R]. Examples: Input: arr[] = {2, 7, 3, 8}, L = 7, R = 20 Output: 197 Explanation: In the range 7 to 20: Sum of multiples of 2: 8 + 10 + 12 + 14 + 16
    7 min read
  • Sum of elements from an array having even parity
    Given an array arr[], the task is to calculate the sum of the elements from the given array which has even parity i.e. the number of set bits is even using bitwise operator. Examples: Input: arr[] = {2, 4, 3, 5, 9} Output: 17 Only 3(0011), 5(0101) and 9(1001) have even parity So 3 + 5 + 9 = 17 Input
    6 min read
  • Sum of array elements which are prime factors of a given number
    Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K. Examples: Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35Output: 12Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 +
    8 min read
  • Sum of all odd frequency elements in an array
    Given an array of integers containing duplicate elements. The task is to find the sum of all odd occurring elements in the given array. That is the sum of all such elements whose frequency is odd in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3} Output : 9 The odd occurring element is 3,
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences