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

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:

    write("1\n");
    write("2\n");
    write("3\n");
    write("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."

Example Code

import std.stdio;

void main() 
{
    for (int i = 1; i <= 10; i++)
        writeln(i);
}

Output

1
2
3
4
5
6
7
8
9
10

Source

Partially based on: The for Statement