Using recursion
Recursion is not used often in NAV, but the option is available and can shorten your code. Recursion is the process by which a function calls itself.
How to do it...
Create a new codeunit from Object Designer.
Add a global function,
Fibonacci
, that returns an integer with no name.The function should take the following parameter:
Name
Type
i
Integer
Write the following code in your
Fibonacci
function.IF (i <= 2) THEN EXIT(1); EXIT ( Fibonacci(i-1) + Fibonacci(i-2) );
Write the following code in your
OnRun
trigger:MESSAGE('Fibonacci(%1) = %2', 4, Fibonacci(4));
When you run the codeunit you will see a window like the one shown in the following screenshot:
How it works...
The Fibonacci sequence is a series of numbers where the value in a certain position is the sum of the number in the previous two positions.
That is: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
A recursive function has two parts. The first is a stopping condition. In our Fibonacci function, the stopping condition...