Suche…


Syntax

  • for (<Initialisierer>; <Schleifenbedingung>; <Schleifenanweisung>) {<Anweisungen>}
  • while (<Bedingung>) {<Anweisungen>}
  • do {<statement>} while (<Bedingung>);
  • foreach (<el>, <collection>)
  • foreach_reverse (<el>, <collection>)

Bemerkungen

Sie können online mit Loops und Foreach spielen .

Für Schleife

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    for (int i = 0; i < arr.length; i++)
    {
        arr[i] *= 2;
    }
    writeln(arr); // [2, 6, 8]
}

While-Schleife

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    int i = 0;
    while (i < arr.length)
    {
        arr[i++] *= 2;
    }
    writeln(arr); // [2, 6, 8]
}

mache

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    int i = 0;
    assert(arr.length > 0, "Array must contain at least one element");
    do
    {
        arr[i++] *= 2;
    } while (i < arr.length);
    writeln(arr); // [2, 6, 8]
}

Für jeden

Foreach ermöglicht eine weniger fehleranfällige und besser lesbare Methode zum Durchlaufen von Sammlungen. Das Attribut ref kann verwendet werden, wenn das iterierte Element direkt geändert werden soll.

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    foreach (ref el; arr)
    {
        el *= 2;
    }
    writeln(arr); // [2, 6, 8]
}

Auf den Index der Iteration kann auch zugegriffen werden:

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    foreach (i, el; arr)
    {
        arr[i] = el * 2;
    }
    writeln(arr); // [2, 6, 8]
}

Iteration in umgekehrter Reihenfolge ist auch möglich:

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    int i = 0;
    foreach_reverse (ref el; arr)
    {
        el += i++; // 4 is incremented by 0, 3 by 1, and 1 by 2
    }
    writeln(arr); // [3, 4, 4]
}

Brechen, fahren Sie fort & Labels

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4, 5];
    foreach (i, el; arr)
    {
        if (i == 0)
            continue; // continue with the next iteration
        arr[i] *= 2;
        if (i == 2)
            break; // stop the loop iteration
    }
    writeln(arr); // [1, 6, 8, 5]
}

Labels können auch zum break oder continue in verschachtelten Schleifen verwendet werden.

void main()
{
    import std.stdio : writeln;
    int[] arr = [1, 3, 4];
    outer: foreach (j; 0..10) // iterates with j=0 and j=1
        foreach (i, el; arr)
        {
            arr[i] *= 2;
            if (j == 1)
                break outer; // stop the loop iteration
    }
    writeln(arr); // [4, 6, 8] (only 1 reaches the second iteration)
}


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow