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:

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

About

VBA Developer

Tagged with: ,