Tail recursion to calculate sum of array elements.
Last Updated :
29 Nov, 2022
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the state of parent call.
Examples:
Input : A[] = {1, 8, 9}
Output : 18
Input : A[] = {2, 55, 1, 7}
Output : 65
For Linear Recursion Method, refer: https://www.geeksforgeeks.org/sum-array-elements-using-recursion/
Logic: Here the key to tail recursion is whatever operation is applied with the function call, maintain it as a separate function parameter.
So, keep the sum of the last elements K elements as a function parameter and return sum when K=0.
C++
#include <bits/stdc++.h>
using namespace std;
int arrSum( int * array, int size, int sum = 0)
{
if (size == 0)
return sum;
return arrSum(array, size - 1, sum + array[size - 1]);
}
int main()
{
int array[] = { 2, 55, 1, 7 };
int size = sizeof (array) / sizeof (array[0]);
cout << arrSum(array, size);
return 0;
}
|
Java
class GFG
{
static int arrSum( int []array, int size, int sum)
{
if (size == 0 )
return sum;
return arrSum(array, size - 1 , sum + array[size - 1 ]);
}
public static void main(String[] args)
{
int array[] = { 2 , 55 , 1 , 7 };
int size = array.length;
System.out.print(arrSum(array, size, 0 ));
}
}
|
Python3
def arrSum(array, size, Sum = 0 ):
if size = = 0 :
return Sum
return arrSum(array, size - 1 ,
Sum + array[size - 1 ])
if __name__ = = "__main__" :
array = [ 2 , 55 , 1 , 7 ]
size = len (array)
print (arrSum(array, size))
|
C#
using System;
class GFG
{
static int arrSum( int []array, int size, int sum)
{
if (size == 0)
return sum;
return arrSum(array, size - 1, sum + array[size - 1]);
}
public static void Main(String[] args)
{
int []array = { 2, 55, 1, 7 };
int size = array.Length;
Console.WriteLine(arrSum(array, size, 0));
}
}
|
Javascript
<script>
function arrSum(array, size, sum = 0)
{
if (size == 0)
return sum;
return arrSum(array, size - 1, sum + array[size - 1]);
}
var array = [2, 55, 1, 7];
var size = array.length;
document.write( arrSum(array, size));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1), If we consider recursive call stack then it would be O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...