For in C

Our first example demonstrates various types of loops in C. Here’s the full source code:

#include <stdio.h>

int main() {
    // The most basic type, with a single condition.
    int i = 1;
    while (i <= 3) {
        printf("%d\n", i);
        i = i + 1;
    }

    // A classic initial/condition/after for loop.
    for (int j = 0; j < 3; j++) {
        printf("%d\n", j);
    }

    // In C, we don't have a direct equivalent to Go's range over an integer.
    // We can simulate it with a standard for loop.
    for (int i = 0; i < 3; i++) {
        printf("range %d\n", i);
    }

    // An infinite loop that will continue until break is called.
    while (1) {
        printf("loop\n");
        break;
    }

    // Demonstrating continue to skip to the next iteration.
    for (int n = 0; n < 6; n++) {
        if (n % 2 == 0) {
            continue;
        }
        printf("%d\n", n);
    }

    return 0;
}

To run the program, save the code in a file named for_loops.c, compile it, and then execute the resulting binary:

$ gcc for_loops.c -o for_loops
$ ./for_loops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Let’s break down the different types of loops used in this C program:

  1. The while loop is used for the most basic type with a single condition.
  2. The classic for loop is directly equivalent in C and Go.
  3. C doesn’t have a built-in range function for integers, so we simulate it with a standard for loop.
  4. An infinite loop in C is typically written as while(1) or for(;;).
  5. The continue statement works the same way in C as it does in Go.

C’s looping constructs are quite flexible and can be used to create various types of iterations. While C doesn’t have some of the more modern conveniences found in Go (like range over integers), it provides all the necessary tools to create equivalent loop structures.