Given an array arr, we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion so that compilers can optimize the code. If the recursive call is the last statement, the compiler can optimize it by eliminating the need to store the parent call's state.
Examples:
Input: arr = [1, 8, 9]
Output: 18
Explanation: The sum of the elements in the array [1, 8, 9] is 18.
Input: arr = [2, 55, 1, 7]
Output: 65
For the Normal Recursion Method, check out this guide: Sum of Array Elements Using Recursion
Approach:
- Extract
arr[size - 1]and add it to thesum. - Call the function again with
size - 1(excluding the last element). - Instead of calculating the sum separately, pass the updated sum in each call.
- Keep reducing
sizeuntil it reaches0. - Once all elements are added, return the accumulated sum as the result.
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum of elements using Tail Recursion
int arrSum(vector<int> &arr, int n, int sum = 0)
{
// Base Case
if (n == 0)
return sum;
// Recursive call
return arrSum(arr, n - 1, sum + arr[n - 1]);
}
int main()
{
// Input array
vector<int> arr = {2, 55, 1, 7};
int n = arr.size();
cout << arrSum(arr, n, 0) << endl;
return 0;
}
class GfG {
// Function to calculate the sum of elements using Tail Recursion
static int arrSum(int[] arr, int n, int sum) {
// Base Case
if (n == 0)
return sum;
// Recursive call
return arrSum(arr, n - 1, sum + arr[n - 1]);
}
public static void main(String[] args) {
int arr[] = { 2, 55, 1, 7 };
int n = arr.length;
System.out.print(arrSum(arr, n, 0));
}
}
def arrSum(arr, n, sum=0):
# Base Case
if n == 0:
return sum
# Recursive call
return arrSum(arr, n - 1, sum + arr[n - 1])
# Driver code
arr = [2, 55, 1, 7]
n = len(arr)
print(arrSum(arr, n, 0))
using System;
class GfG {
// Function to calculate the sum of elements using Tail
// Recursion
static int arrSum(int[] arr, int n, int sum)
{
// Base Case
if (n == 0)
return sum;
// Recursive call
return arrSum(arr, n - 1, sum + arr[n - 1]);
}
public static void Main()
{
int[] arr = { 2, 55, 1, 7 };
int n = arr.Length;
Console.WriteLine(arrSum(arr, n, 0));
}
}
function arrSum(arr, n, sum = 0)
{
// Base Case
if (n === 0)
return sum;
// Recursive call
return arrSum(arr, n - 1, sum + arr[n - 1]);
}
// Driver code
let arr = [ 2, 55, 1, 7 ];
let n = arr.length;
console.log(arrSum(arr, n, 0));
Output
65
Time Complexity: O(n), where n is the length of array.
Auxiliary Space: O(n), due to recursive function calls stored in the call stack.