for Loop
This lesson explains the for loop, its syntax and implementation in D.
for
loop #
The for
loop serves the same purpose as the while loop. for
makes it possible to put the definitions and expressions concerning the loop’s iteration on the same line.
Although for
is used much less than foreach
in practice, it is important to understand the for loop first. We will see foreach
in a later chapter.
The sections of the while
loop #
The while
loop evaluates the loop condition and continues executing the loop as long as that condition is true. For example, a loop to print the numbers between 1 and 10 may check the condition less than 11.
To be compilable as D code, number
must have been defined before its first use:
int number = 1;
while (number < 11)
Iterating the loop can be achieved by incrementing the number at the end of the loop:
++number;
Finally, there is the actual work within the loop body:
writeln(number);
These four sections can be combined into the desired loop as follows:
Get hands-on with 1400+ tech skills courses.