The for Loop
Part of TutorialFundamentals
Description
How to do the same thing over and over again.
Example
Most people don't like to do monotonous tasks over and over again (especially not a lazy programmer). That's where the for loop comes in. You could write a program like this:
printf("1\n");
printf("2\n");
printf("3\n");
printf("4\n");
...
but that's no fun. The for statement allows the programmer step back and just say to the computer, "count from 1 to 10, and print each number."
import std.stdio; int main() { for (int i = 1; i <= 10; i++) writefln(i); return 0; }
Equivalent Example in QuickBASIC
DIM I% FOR I% = 1 TO 10 PRINT I% NEXT I%
Output
1 2 3 4 5 6 7 8 9 10
More Information about writef
Note that you can send data other than strings directly to writef. In this example, the expression writefln(i) yields the same results as writefln("%d", i). Its a very convenient shorthand, although one has to be careful when working with string variables. Anytime the first parameter to writef will be, or likely could be, a string variable not meant for formatting, use the syntax writef("%s", var) to ensure the variable's data isn't checked for format specifiers. Also note that the %s specifier works with any data type, not just strings, and simply uses the default formatting for the given type, such as %d for integers.
Testing
Tested with DMD 1.010 on Windows 2000.
Source
Partially based on: The for Statement
