Title here
Summary here
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:
while
loop is used for the most basic type with a single condition.for
loop is directly equivalent in C and Go.range
function for integers, so we simulate it with a standard for
loop.while(1)
or for(;;)
.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.