Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes between Version 7 and Version 8 of ForLoopExample

Show
Ignore:
Author:
nascent (IP: 67.110.217.136)
Timestamp:
05/30/10 19:53:22 (14 years ago)
Comment:

Updated with D2.x example.

Legend:

Unmodified
Added
Removed
Modified
  • ForLoopExample

    v7 v8  
    1111Most 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: 
    1212{{{ 
    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"); 
    1717    ... 
    1818}}} 
    1919but 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." 
    2020 
     21==== D1.x ==== 
    2122{{{ 
    2223#!d 
    3132}}} 
    3233 
     34==== D2.x ==== 
     35{{{ 
     36#!d 
     37import std.stdio; 
     38 
     39int main()  
     40{ 
     41  for (int i = 1; i <= 10; i++) 
     42    writeln(i); 
     43  return 0; 
     44} 
     45}}} 
    3346 
    3447== Equivalent Example in QuickBASIC == 
    5770}}} 
    5871 
    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 SP3 
    70 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  
    7372== Source == 
    7473