Program to Find the Sum of all Array Elements in C++.

Given an Array of integers of size n. Find the Sum of all the elements present in the given Array.

Example 1: 
Input: arr[] = {2, 5, 9, 7, 10}
Output: 33
Explanation: 2 + 5 + 9 + 7 + 10 = 33

Example 2: 
Input: arr[] = {5, -2, 10, 7, 2}
Output: 22
Explanation: 5 + (- 2) + 10 + 7 + 2 = 22

Method 1: Iterative method using for loop.

Steps to find the Sum of Array elements:
  • Declare one sum variable to store the sum of the array and initialize it with 0.  
  • Run a for loop through all the array elements and keep on adding them one by one to sum the variable.(sum = sum + arr[i])
  • Print the value of the sum. 

C++ Program to find the sum of all Array Elements.

//C++ Program to find sum of array elements
#include<iostream>
using namespace std;

//Function to return sum of array
int sum(int arr[], int n){
    int sum = 0;

    for(int i = 0; i < n; i++){
        sum = sum + arr[i];
    }

    return sum;
}

int main(){
    int arr[] = {2, 5, 9, 7, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);

    cout<<"Sum of Array Elements: "<<sum(arr, n);
}
Output:
Sum of Array Elements: 33
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Method 2: Using Recursion.

The base case of our recursive function is when the size of the array will become 0 and until we hit the base case we keep on calling our sum function each this by decreasing the size of the array by one.

//C++ Program to find sum of array elements
#include<iostream>
using namespace std;

//Recursive Function to return sum of array
int sum(int arr[], int n){
    //base case
    if(n == 0){
        return 0;
    }
    else{
        //Calling the function recursively
        return arr[0] + sum(arr+1, n-1);
    }
}

int main(){
    int arr[] = {2, 5, 9, 7, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);

    cout<<"Sum of Array Elements: "<<sum(arr, n);
}
Output:
Sum of Array Elements: 33
    • Time Complexity: O(n)
    • Space Complexity: O(1)

    ⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

    Similar Posts

    No comments:

    Post a Comment


    CLOSE ADS
    CLOSE ADS