Repeating code using a loop
Looping is an essential part of dealing with records in NAV. Using a FOR
loop is a common way to iterate over multiple lines of code. This recipe will show you how to construct a FOR
loop and use it.
How to do it...
Create a new codeunit from Object Designer.
Add the following global variables:
Name
Type
n
Integer
i
Integer
Factorial
Integer
Add the following code to the
OnRun
trigger of the codeunit:Factorial := 1; n := 4; FOR i := 1 TO n DO Factorial := Factorial * i; MESSAGE('Factorial of %1 = %2', n, Factorial);
Save and close the codeunit.
When you run the codeunit you will see a window similar to the following screenshot:
How it works...
A FOR
loop has four parts: a counter, a starting value, the step to be taken, and an ending value. In this code, our counter variable is "i". The starting value is 1 and the ending value is "n", which in this case has been assigned to the value 4.
Each time the loop iterates, the value of "i" is increased by one ...