Batch Script - Recursive Functions



The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. We can now have the ability to call a function recursively making sure each level of recursion works with its own set of variables even though variable names are being reused.

Following example shows how recursive functions can be used.

Example

The example 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 to 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.

@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
:myFibo -- calculate recursively
:myFibo -- calculate recursively the next Fibonacci number greater or equal to a 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

Output

The above command produces the following output.

The next Fibonacci number greater or equal 1000000000 is 1134903170.
batch_script_functions.htm
Advertisements