Skip to content
  • Loops: for, while, do-while · C

Loops: for, while, do-while

LearnViaNotes @learnvianotes· 3 min read

Three loop forms, plus break, continue and (rarely) goto. Pick for when you count, while when you wait for a condition, do-while when the body must run at least once.

The three loops

C
#include <stdio.h>

int main(void) {
    for (int i = 0; i < 5; i++)          /* init; condition; step */
        printf("%d ", i);
    printf("\n");

    int n = 1234, digits = 0;
    while (n != 0) {                     /* test before each iteration */
        n /= 10;
        digits++;
    }
    printf("digits = %d\n", digits);

    int k = 100;
    do {                                 /* body runs at least once */
        printf("k = %d\n", k);
    } while (k < 10);
    return 0;
}
Output
0 1 2 3 4
digits = 4
k = 100

break and continue

C
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;   /* skip even numbers */
        if (i > 7) break;           /* leave the loop entirely */
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
Output
1 3 5 7

Nested loops and patterns

C
#include <stdio.h>

int main(void) {
    int n = 4;
    for (int row = 1; row <= n; row++) {
        for (int s = 0; s < n - row; s++) putchar('.');
        for (int star = 0; star < 2 * row - 1; star++) putchar('*');
        putchar('\n');
    }
    return 0;
}
Output
...*
..***
.*****
*******

Breaking out of nested loops: goto

C
#include <stdio.h>

int main(void) {
    int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int target = 5;
    for (int r = 0; r < 3; r++)
        for (int c = 0; c < 3; c++)
            if (grid[r][c] == target) {
                printf("found at (%d,%d)\n", r, c);
                goto done;              /* one of the few acceptable uses */
            }
    printf("not found\n");
done:
    return 0;
}
Output
found at (1,1)

Loop idioms

IdiomCode
Infinite loopfor (;;) { … } or while (1) { … }
Iterate an arrayfor (size_t i = 0; i < n; i++)
Count down with size_tfor (size_t i = n; i-- > 0; ) (avoids the unsigned wrap trap)
Read until EOFwhile ((c = getchar()) != EOF)
Two indexesfor (int i = 0, j = n - 1; i < j; i++, j--)
C
#include <stdio.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    size_t n = sizeof a / sizeof a[0];
    for (size_t i = n; i-- > 0; )           /* safe reverse loop with unsigned index */
        printf("%d ", a[i]);
    printf("\n");
    for (int i = 0, j = (int)n - 1; i < j; i++, j--) {   /* reverse in place */
        int t = a[i]; a[i] = a[j]; a[j] = t;
    }
    for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Output
5 4 3 2 1
5 4 3 2 1

What is the difference between while and do-while?

Why is for (unsigned i = n - 1; i >= 0; i--) an infinite loop?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report