Home C++ Tutorial Sum of array elements using recursion

Sum of array elements using recursion

by Anup Maurya
2 minutes read

In this article, we will explore how to calculate the sum of array elements using recursion in C++. We will provide a clear explanation of the concept and then walk through a step-by-step example.

Recursion is a powerful programming technique that allows a function to call itself in order to solve a problem. It is often used to simplify complex problems and can be a valuable tool in a programmer’s toolkit.

Approach

Recursion involves breaking down a problem into smaller, more manageable subproblems. In the context of summing array elements, we can think of the problem as follows:

  1. If the array is empty (i.e., it has no elements), the sum is 0.
  2. If the array has one element, the sum is that element.
  3. If the array has more than one element, we can break it down into two parts:
    • The first element (the head) and
    • The remaining elements (the tail).

We can calculate the sum of the array by adding the head to the sum of the tail, where the sum of the tail is calculated using the same recursive function.

Sum of Array Elements Using Recursion

#include <iostream>
using namespace std;

// Recursive function to calculate the sum of elements in an array
int sumArray(int arr[], int size) {
    // Base case: If the array is empty, return 0
    if (size == 0) {
        return 0;
    }
     if (size == 1) {
        return arr[0];
    }
    // Recursive case: Calculate the sum of the tail and add it to the head
    else {
        return arr[0] + sumArray(arr + 1, size - 1);
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Calculate the sum of the array elements using recursion
    int sum = sumArray(arr, size);

    cout << "The sum of the array elements is: " << sum << endl;

    return 0;
}
C++

Explanation of the Code

  1. We define a recursive function sumArray that takes two arguments: an array arr and its size size.
  2. In the base case, when size is 0 (i.e., the array is empty), the function returns 0 because there are no elements to sum.
  3. In the recursive case, we calculate the sum of the array by adding the first element arr[0] to the result of the recursive call sumArray(arr + 1, size - 1), where arr + 1 represents the tail of the array, and size - 1 indicates the reduced size of the array.
  4. In the main function, we create an example integer array arr and calculate its sum using the sumArray function. We then print the result to the console.

related posts

Leave a Comment

Enable Notifications OK No thanks