SyntaxStudy
Sign Up
C for, while, and do-while Loops
C Beginner 1 min read

for, while, and do-while Loops

C provides three looping constructs. The `for` loop is most natural when you know the number of iterations in advance; it bundles the initializer, condition, and update into a single header line. The `while` loop checks its condition before each iteration and is best when the loop count is not known ahead of time. The `do-while` loop checks its condition after each iteration, guaranteeing that the body executes at least once — useful for input validation and menu loops. Inside any loop, `break` immediately exits the loop and `continue` skips the rest of the current iteration and jumps to the next condition check. Nested loops each have their own `break` and `continue` scope. To exit from nested loops you can use a flag variable, restructure with a function that uses `return`, or — rarely and carefully — use `goto` to jump out of multiple levels. Infinite loops are sometimes intentional, especially in embedded systems and servers. The idiom `while (1)` or `for (;;)` creates a loop that runs forever unless a `break` or `return` is encountered. Always ensure such loops have a well-defined and reachable exit condition to avoid hanging programs.
Example
#include <stdio.h>

int main(void)
{
    /* for loop — counting up */
    printf("for:     ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", i);
    }
    printf("\n");

    /* for loop — counting down */
    printf("reverse: ");
    for (int i = 4; i >= 0; i--) {
        printf("%d ", i);
    }
    printf("\n");

    /* while loop */
    int n = 1;
    printf("while powers of 2: ");
    while (n <= 64) {
        printf("%d ", n);
        n *= 2;
    }
    printf("\n");

    /* do-while — body runs at least once */
    int input;
    do {
        printf("Enter 1-10: ");
        scanf("%d", &input);
    } while (input < 1 || input > 10);
    printf("Valid input: %d\n", input);

    /* break and continue */
    printf("skip evens, stop at 9: ");
    for (int i = 0; i < 15; i++) {
        if (i % 2 == 0) continue;
        if (i == 9)     break;
        printf("%d ", i);
    }
    printf("\n");

    return 0;
}