Industriële fabricage
Industrieel internet der dingen | Industriële materialen | Onderhoud en reparatie van apparatuur | Industriële programmering |
home  MfgRobots >> Industriële fabricage >  >> Industrial programming >> C Taal

C-lussen: while, for, do-while en luscontrole

Waarom lussen?

Lussen herhalen een blok code zolang een voorwaarde geldt. C biedt drie basislussoorten.

while lus

Test voorwaarde voor elke iteratie.

while (voorwaarde) {
    // body
}

Voorbeeld

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
// Output: 1 2 3 4 5

for lus

Compacte syntaxis met initialisatie, voorwaarde, increment.

for (init; voorwaarde; increment) {
    // body
}

Voorbeeld

for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
// Output: 1 2 3 4 5

Alle drie delen optioneel: for (;;) = oneindige lus.

do-while lus

Test voorwaarde na de body → body draait minimaal één keer.

do {
    // body
} while (voorwaarde);

Voorbeeld

int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);
// Output: 1 2 3 4 5

Geneste lussen

Lussen in lussen (bijv. voor matrices, patronen).

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        printf("(%d,%d) ", i, j);
    }
    printf("\n");
}

Luscontrole-statements

StatementEffect
breakVerlaat lus (of switch) direct; gaat door na lus
continueSpringt naar volgende iteratie (her-evalueert voorwaarde)
goto label;Springt naar gelabelde statement (gebruik spaarzaam!)

Voorbeeld break en continue

for (int i = 1; i <= 10; i++) {
    if (i == 3) continue;   // sla 3 over
    if (i == 8) break;      // stop bij 8
    printf("%d ", i);
}
// Output: 1 2 4 5 6 7

Oneindige lus

for (;;) {
    // draait voor eeuwig
    // afbreken met Ctrl+C
}

Of while (1). Gebruikelijk voor event-loops, servers, embedded systemen.

Tip: Kies for als aantal iteraties bekend is, while voor onbekend aantal, do-while als body min. 1× moet draaien.

C Taal

  1. Phase‑Locked Loops (PLL's): Fundamenten, Toepassingen en Ontwerp Best Practices
  2. De C# Switch Statement: Syntaxis, Voorbeelden & Best Practices
  3. C# While en Do-While Loops: Syntaxis, Voorbeelden en Best Practices
  4. C# For Loops: Syntaxis, Stroom en Praktische Voorbeelden
  5. C# Break Statement: Hoe en Wanneer Te Gebruiken
  6. C# Continue Statement: Effectief Lusiteraties Overslaan
  7. C# foreach Loops: Arrays en Collecties Eenvoudig Itereren
  8. C++ for loops: stap-voor-stap gids
  9. C++ break statement: loop controle onder de knie
  10. C-basissyntax: Tokens, structuur en puntkomma's
  11. Python-lussen beheersen: For, While, Break, Continue en Enumerate uitgelegd