C Loops

C loops repeat a block of code while a condition is true. C has three kinds: while, do while and for. They can all do the same job, but each fits certain situations best.

The while Loop

A while loop checks its condition before each repetition.

#include <stdio.h>

int main(void) {
    int count = 1;
    while (count <= 3) {
        printf("Count: %d\n", count);
        count++;
    }
    return 0;
}
Count: 1
Count: 2
Count: 3

The do while Loop

A do while loop checks the condition after the body, so the body always runs at least once.

#include <stdio.h>

int main(void) {
    int n = 10;
    do {
        printf("n = %d\n", n);
        n++;
    } while (n < 5);
    return 0;
}
n = 10

The for Loop in C

A for loop puts the start, condition and update in one line, which is ideal when you know how many times to repeat.

#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }
    printf("Sum of 1..5 = %d\n", sum);
    return 0;
}
Sum of 1..5 = 15

break and continue

break exits the loop immediately. continue skips the rest of the current iteration and moves on to the next.

#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;          // stop after 7
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
1 3 5 7 

Nested Loops

A loop inside a loop is useful for grids and tables.

#include <stdio.h>

int main(void) {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 3; col++) {
            printf("%3d", row * col);
        }
        printf("\n");
    }
    return 0;
}
  1  2  3
  2  4  6
  3  6  9

Frequently asked questions

What is the difference between while and do while in C?

A while loop may run zero times because it checks first. A do while loop always runs at least once because it checks after the body.

When should I use a for loop instead of while?

Use for when you are counting or know the number of iterations. Use while when you repeat until something happens, such as reading input until the user types quit.

How do I write an infinite loop in C?

Use while (1) { ... } or for (;;) { ... }, and exit it with break or return when needed.