Changes between Version 7 and Version 8 of ForLoopExample
- Timestamp:
- 05/30/10 19:53:22 (14 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
ForLoopExample
v7 v8 11 11 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: 12 12 {{{ 13 printf("1\n");14 printf("2\n");15 printf("3\n");16 printf("4\n");13 writef("1\n"); 14 writef("2\n"); 15 writef("3\n"); 16 writef("4\n"); 17 17 ... 18 18 }}} 19 19 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." 20 20 21 ==== D1.x ==== 21 22 {{{ 22 23 #!d 31 32 }}} 32 33 34 ==== D2.x ==== 35 {{{ 36 #!d 37 import std.stdio; 38 39 int main() 40 { 41 for (int i = 1; i <= 10; i++) 42 writeln(i); 43 return 0; 44 } 45 }}} 33 46 34 47 == Equivalent Example in QuickBASIC == 57 70 }}} 58 71 59 60 == More Information about '''writef''' ==61 62 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.63 64 65 == Testing ==66 67 Tested with DMD 1.010 on Windows 2000.68 69 Tested with DMD 2.033 on Windows XP SP370 Requires the formatting argument for writefln("%d", i) otherwise get a static assert error.71 Alternatively `writeln(i)` can be used -- there is no need for formatted output here.72 73 72 == Source == 74 73