VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tail-recursion-to-calculate-sum-of-array-elements/

⇱ Sum of array - Tail Recursive Solution - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of array - Tail Recursive Solution

Last Updated : 10 Sep, 2025

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 the sum.
  • 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 size until it reaches 0.
  • Once all elements are added, return the accumulated sum as the result.

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. 


Comment
Article Tags: