Repeating code using a loop
Looping is an essential part of any data manipulation. Same as the other programming languages, C/AL offers a variety of looping methods. The following recipe will help you understand how to use the FOR
loop in C/AL code.
How to do it...
Let's start by creating a new codeunit from Object Designer.
Then add the following global variables:
Name
Type
n
Integer
i
Integer
Factorial
Integer
Now write the following code in the
OnRun
trigger of the codeunit:Factorial := 1; n := 4; FOR i := 1 TO n DO BEGIN Factorial := Factorial * i; MESSAGE('Factorial of %1 = %2', n, Factorial); END;
To complete the task, save and close the codeunit.
On execution of the codeunit, you should 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...