Program to find sum of elements in a given array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of n integer values. Our task is to create a Program to find sum of elements in a given array in C++.

Program Description − For the given array, we will add up all elements and return the sum.

Let’s take an example to understand the problem

Input

arr[] = {3, 1, 7, 2, 9, 10}

Output

32

Explanation

Sum = 3 + 1 + 7 + 2 + 9 + 10 = 32

Solution Approach

To find the sum of elements of the array, we will traverse the array and extract each element of the array and add them to sumVal which will return the sum.

We can do by two ways,

  • Using recursion
  • Using iteration

Program to show the implement Recursive approach

Example

 Live Demo

#include <iostream>
using namespace std;
int calcArraySum(int arr[], int n){
   if(n == 1){
      return arr[n-1];
   }
   return arr[n-1] + calcArraySum(arr, n-1);
}
int main(){
   int arr[] = {1, 4, 5, 7, 6};
   int n = sizeof(arr)/ sizeof(arr[0]);
   cout<<"The sum of elements in a given array is"<<calcArraySum(arr, n);
   return 0;
}

Output

The sum of elements in a given array is 23

Program to show the implement Iterative approach

Example

 Live Demo

#include <iostream>
using namespace std;
int calcArraySum(int arr[], int n){
   int sumVal = 0;
   for(int i = 0; i < n; i++){
      sumVal += arr[i];
   }
   return sumVal;
}
int main(){
   int arr[] = {1, 4, 5, 7, 6};
   int n = sizeof(arr)/ sizeof(arr[0]);
   cout<<"The sum of elements in a given array is"<<calcArraySum(arr, n);
   return 0;
}

Output

The sum of elements in a given array is 23
raja
Published on 27-May-2020 13:08:01
Advertisements