Tail recursion to calculate sum of array elements.
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; } |
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 |
65
Time Complexity: O(n)
Recommended Posts:
- Tail Recursion
- Tail Recursion for Fibonacci
- Sum of even elements of an Array using Recursion
- Program to Calculate e^x by Recursion
- C++ Program to print an Array using Recursion
- Program to check if an array is palindrome or not using Recursion
- Tail Call Elimination
- Flip minimum signs of array elements to get minimum sum of positive elements possible
- Maximize array elements upto given number
- Print all possible combinations of r elements in a given array of size n
- Number of ways to choose elements from the array such that their average is K
- Recursion
- Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion
- Find the value of ln(N!) using Recursion
- Print 1 to 100 in C++, without loop and recursion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : rituraj_jain



