Table of Contents
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:
- If the array is empty (i.e., it has no elements), the sum is 0.
- If the array has one element, the sum is that element.
- 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
- We define a recursive function
sumArray
that takes two arguments: an arrayarr
and its sizesize
. - 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. - In the recursive case, we calculate the sum of the array by adding the first element
arr[0]
to the result of the recursive callsumArray(arr + 1, size - 1)
, wherearr + 1
represents the tail of the array, andsize - 1
indicates the reduced size of the array. - In the
main
function, we create an example integer arrayarr
and calculate its sum using thesumArray
function. We then print the result to the console.