For in Cilk

#include <stdio.h>
#include <cilk/cilk.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 loop.
    for (int j = 0; j < 3; j++) {
        printf("%d\n", j);
    }

    // Another way of accomplishing the basic "do this N times" iteration.
    // Cilk doesn't have a direct equivalent to Go's range over integers,
    // so we'll use a regular for loop.
    for (int i = 0; i < 3; i++) {
        printf("range %d\n", i);
    }

    // A loop without a condition will repeat until a break or return.
    while (1) {
        printf("loop\n");
        break;
    }

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

    return 0;
}

In Cilk, which is an extension of C, we use similar looping constructs to those found in C. Here are the main differences and adaptations:

  1. We use #include <stdio.h> for input/output functions and #include <cilk/cilk.h> for Cilk-specific features (although we don’t use any Cilk-specific features in this example).

  2. The fmt.Println() function is replaced with printf().

  3. Cilk (and C) don’t have a direct equivalent to Go’s range over integers, so we use a regular for loop instead.

  4. The infinite loop is implemented using while (1) instead of for without conditions.

  5. Variable declarations are typically done at the beginning of a block in C/Cilk, so we’ve adjusted the placement of some variable declarations.

To compile and run this Cilk program:

$ cilk++ -o for for.cilk
$ ./for
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Note that Cilk is primarily used for parallel programming, but this example doesn’t showcase any parallelism. For more complex examples involving parallel constructs, you would use Cilk-specific keywords like cilk_spawn and cilk_sync.

Cilk provides powerful constructs for parallel programming, which we’ll see in later, more advanced examples.