The Wayback Machine - https://web.archive.org/web/20240717181820/https://www.geeksforgeeks.org/tail-recursion-to-calculate-sum-of-array-elements/
Open In App

Tail recursion to calculate sum of array elements.

Last Updated : 29 Nov, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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;
 
// Tail recursive function
int arrSum(int* array, int size, int sum = 0)
{
    // Base Case
    if (size == 0)
        return sum;
 
    // Function Call Observe sum+array[size-1]
    // to maintain sum of elements
    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




// Java implementation of the given approach.
class GFG
{
 
// Tail recursive function
static int arrSum(int []array, int size, int sum)
{
    // Base Case
    if (size == 0)
        return sum;
 
    // Function Call Observe sum+array[size-1]
    // to maintain sum of elements
    return arrSum(array, size - 1, sum + array[size - 1]);
}
 
// Driver code
public static void main(String[] args)
{
    int array[] = { 2, 55, 1, 7 };
    int size = array.length;
    System.out.print(arrSum(array, size, 0));
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 implementation of the given approach.
 
# Tail recursive function
def arrSum(array, size, Sum = 0):
 
    # Base Case
    if size == 0:
        return Sum
 
    # Function Call Observe sum+array[size-1]
    # to maintain sum of elements
    return arrSum(array, size - 1,
            Sum + array[size - 1])
 
# Driver Code
if __name__ == "__main__":
 
    array = [2, 55, 1, 7]
    size = len(array)
    print(arrSum(array, size))
 
# This code is contributed by Rituraj Jain


C#




     
// C# implementation of the given approach.
using System;
 
class GFG
{
 
// Tail recursive function
static int arrSum(int []array, int size, int sum)
{
    // Base Case
    if (size == 0)
        return sum;
 
    // Function Call Observe sum+array[size-1]
    // to maintain sum of elements
    return arrSum(array, size - 1, sum + array[size - 1]);
}
 
// Driver code
public static void Main(String[] args)
{
    int []array = { 2, 55, 1, 7 };
    int size = array.Length;
    Console.WriteLine(arrSum(array, size, 0));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Tail recursive function
function arrSum(array, size, sum = 0)
{
    // Base Case
    if (size == 0)
        return sum;
 
    // Function Call Observe sum+array[size-1]
    // to maintain sum of elements
    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>   


Output: 

65

 

Time Complexity: O(n)
Auxiliary Space: O(1), If we consider recursive call stack then it would be O(n)
 



Previous Article
Next Article

Similar Reads

Tail vs. Non-Tail Recursion
Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion. 1) Definition:Tail recursion is defined by having the recursive call as the last operation in the function before returningfunction factorial
3 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n &lt; 0
8 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the function. Writing a tail recursion is little tric
4 min read
Tail Recursion in Python
Tail recursion is a special case of recursion where the recursive call is the last operation in the function. Therefore, the function returns the result of the recursive call directly, without performing any additional computation after the call. In some languages, tail-recursive functions can be transformed into iterative loops to avoid growing th
3 min read
Program to calculate value of nCr using Recursion
Given two numbers N and r, find the value of NCr using recursion Examples: Input: N = 5, r = 2Output: 10Explanation: The value of 5C2 is 10 Input: N = 3, r = 1Output: 3 Approach 1: One very interesting way to find the C(n,r) is the recursive method which is based on the recursive equation. C(n,r) = C(n-1,r-1) + C(n-1,r) Below is the implementation
5 min read
Write a program to Calculate Size of a tree | Recursion
Size of a tree is the number of elements present in the tree. Size of the below tree is 5. Size() function recursively calculates the size of a tree. It works as follows:Size of a tree = Size of left subtree + 1 + Size of right subtree. Recommended PracticeSize of Binary TreeTry It!Algorithm: size(tree)1. If tree is empty then return 02. Else (a) G
14 min read
Program to Calculate e^x by Recursion ( using Taylor Series )
The value of the Exponential function can be calculated using Taylor Series. [Tex]e^x[/Tex] = 1 + x/1! + [Tex]x^2[/Tex]/2! + [Tex]x^3[/Tex]/3! + ...... + until n termsAs the number of terms increases the more precise value of ex is obtained. To find e^x using the recursive function, we need to use static variables. A function can return only one va
5 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg