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...
Let's create a new codeunit from Object Designer.
Then add a global function called
Fibonacci
that returns an integer with no name.Provide the following parameters for the function:
Name
Type
i
Integer
Now write the following code to the
Fibonacci
function:IF (i <= 2) THEN EXIT(1); EXIT ( Fibonacci(i-1) + Fibonacci(i-2) );
Write the following code in the
OnRun
trigger of the codeunit:MESSAGE('Fibonacci(%1) = %2', 4, Fibonacci(4));
It's time to save and close the codeunit.
On execution of the codeunit, you should see a window similar to 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, and so on.
A recursive function has two parts. The...