VBA – Sum array with recursion

This is what Wikipedia says about Recursion:

Recursion occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics and computer science, where a function being defined is applied within its own definition.

In this article, I will simply show how to make a recursion for sum of Array. It is strongly not advisable to sum an array like this in VBA, as far as it is really a slow method, but it may be useful, to get more insight concerning how the recursion works.

In general, if we have an array, in order to get the sum of its elements with recursion, we need to get the sum of all the elements without the last one and sum it with the last one. This should be repeated, until we get the first element. Once we have the first element, we reach the “bottom” of the recursion and we may start calculating back.

This is how the code looks like:

Option Explicit

'---------------------------------------------------------------------------------------
' Method : TestMe
' Date   : 22.01.2018
' Purpose: Do not try to sum array like this :)
'           Sample for recursion sum.
'---------------------------------------------------------------------------------------
Public Sub TestMe()
    Debug.Print SumArrayRecursion(Array(1, 2, 4, 8))
End Sub

Public Function SumArrayRecursion(arr As Variant) As Long

    Dim cnt     As Long
    Dim newArr  As Variant
    
    If LBound(arr) = UBound(arr) Then
        SumArrayRecursion = arr(0)
        Exit Function
    End If
    
    ReDim newArr(UBound(arr) - 1)
    For cnt = LBound(newArr) To UBound(newArr)
        newArr(cnt) = arr(cnt)
    Next cnt
    
    Debug.Print printArray(newArr)
    SumArrayRecursion = SumArrayRecursion(newArr) + newArr(UBound(newArr))
    
End Function

Public Function printArray(arr As Variant) As String
    Dim cnt As Long
    For cnt = LBound(arr) To UBound(arr)
        printArray = printArray & " " & arr(cnt)
    Next cnt
End Function

As you see, in the SumArrayRecursion we are having a bottom of recursion (LBound(arr) = Ubound(arr)). This may be written as “Ubound = 0” as well, but I have considered the other way fancier. Once we reach the bottom, we may start providing value to the recursion’s function SumArrayRecursion = SumArrayRecursion(newArr) + newArr(UBound(newArr)) .

These are my previous articles for recursion:

VBA – Nested loops with recursion

C# – Three Algorithms For Fibonacci Numbers