Difference between revisions of "Looping over integers"
(Created page with "Looping over a range of consecutive integers is a very common programming task. In the family of C-like languages (C, C++, Java, etc.), the usual way to write this is somethin...") |
m |
||
(2 intermediate revisions by one other user not shown) | |||
Line 3: | Line 3: | ||
<syntaxhighlight lang=C> | <syntaxhighlight lang=C> | ||
int i; | int i; | ||
− | for (i=0; i < | + | for (i=0; i < 100; i++) |
{ | { | ||
// loop body here | // loop body here | ||
Line 9: | Line 9: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | D also supports exactly the same syntax, but its much more powerful ''foreach'' construct coupled with its slicing syntax allows you to write such loops in a much more readable way: | + | D also supports exactly the same syntax, but its much more powerful '''foreach''' construct coupled with its slicing syntax allows you to write such loops in a much more readable way: |
<syntaxhighlight lang=D> | <syntaxhighlight lang=D> | ||
− | foreach (i; 0 .. | + | foreach (i; 0 .. 100) |
{ | { | ||
// loop body here | // loop body here | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | [[Category:CommonIdiom]] |
Latest revision as of 10:25, 14 November 2014
Looping over a range of consecutive integers is a very common programming task. In the family of C-like languages (C, C++, Java, etc.), the usual way to write this is something like:
int i;
for (i=0; i < 100; i++)
{
// loop body here
}
D also supports exactly the same syntax, but its much more powerful foreach construct coupled with its slicing syntax allows you to write such loops in a much more readable way:
foreach (i; 0 .. 100)
{
// loop body here
}