Recursive Functions

Tadaaah!!!

Description: Being able to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller we are now able to call a function recursively making sure each level of recursion works with its own set of variables even thought variable names are being reused.

Example: The next example below shows how to calculate a Fibonacci number recursively. The recursion stops when the Fibonacci algorism reaches a number greater or equal to a given input number.
The example starts with the numbers 0 and 1 the :myFibo function calls itself recursively to calculate the next Fibonacci number until it finds the Fibonacci number greater or equal 1000000000.

The first argument of the myFibo function is the name of the variable to store the output in. This variable must be initialized to the Fibonacci number to start with and will be used as current Fibonacci number when calling the function and will be set to the subsequent Fibonacci number when the function returns.
Script: Download: BatchTutoFuncRecurs.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
@echo off

set "fst=0"
set "fib=1"
set "limit=1000000000"
call:myFibo fib,%fst%,%limit%
echo.The next Fibonacci number greater or equal %limit% is %fib%.

echo.&pause&goto:eof


::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myFibo  -- calculate recursively the next Fibonacci number greater or equal to a limit
::       -- %~1: return variable reference and current Fibonacci number
::       -- %~2: previous value
::       -- %~3: limit
SETLOCAL
set /a "Number1=%~1"
set /a "Number2=%~2"
set /a "Limit=%~3"
set /a "NumberN=Number1 + Number2"
if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit%
(ENDLOCAL
    IF "%~1" NEQ "" SET "%~1=%NumberN%"
)
goto:eof
Script Output:
 DOS Script Output
The next Fibonacci number greater or equal 1000000000 is 1134903170.

Press any key to continue . . .