Zoeken…


Syntaxis

  • voor (<initializer>; <lusvoorwaarde>; <lusinstructie>) {<statements>}
  • terwijl (<voorwaarde>) {<statements>}
  • doe {<statements>} while (<voorwaarde>);
  • foreach (<el>, <collection>)
  • foreach_reverse (<el>, <collection>)

Opmerkingen

Je kunt online spelen met loops en foreach .

For loop

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]
}

Herhalingslus

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]
}

doen terwijl

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]
}

foreach

Foreach biedt een minder foutgevoelige en beter leesbare manier om collecties te herhalen. Het kenmerk ref kan worden gebruikt als we het iteratieve element direct willen wijzigen.

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

De index van de iteratie is ook toegankelijk:

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

Iteratie in omgekeerde volgorde is ook mogelijk:

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]
}

Break, doorgaan & 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 kunnen ook worden gebruikt om binnen geneste lussen te break of continue te break .

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
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow