© Mikael Olsson 2019
Mikael OlssonModern C Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-4288-9_9

9. Loops

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, Finland
 

There are three looping structures in C, all of which are used to execute a specific code block multiple times. Just as with the conditional if statement, the curly brackets for the loops can be left out if there is only one statement in the code block.

While Loop

The while loop runs through the code block only if its condition is true, and it will continue looping for as long as the condition remains true. Bear in mind that the condition is only checked at the start of each iteration (each loop).
int i = 0;
while (i < 10) {
  printf("%d", i++); /* 0-9 */
}

Do-While Loop

The do-while loop works in the same way as the while loop, except that it checks the condition after the code block. It will therefore always run through the code block at least once. Notice that this loop ends with a semicolon.
int j = 0;
do {
  printf("%d", j++); /* 0-9 */
} while (j < 10);

For Loop

The for loop is used to run through a code block a specific number of times. It uses three parameters. The first one initializes a counter and is always executed once before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment of the counter and is executed at the end of each iteration.
int k;
for (k = 0; k < 10; k++) {
  printf("%d", k); /* 0-9 */
}
Since the C99 standard the first parameter may contain a declaration, typically a counter variable. The scope of this variable is limited to the for loop.
for (int k = 0; k < 10; k++) {
  printf("%d", k); /* 0-9 */
}
The for loop has several variations. One such variation is to split the first and third parameters into several statements by using the comma operator.
int k, m;
for (k = 0, m = 0; k < 10; k++, m--) {
  printf("%d", k+m); /* 000... (10x) */
}
Another option is to leave out any one of the parameters. If all parameters are left out, it becomes a never-ending loop, unless there is another exit condition defined .
for (;;) { /* infinite loop */ }

Break and Continue

There are two jump statements that can be used inside loops: break and continue . The break keyword ends the loop structure, and continue skips the rest of the current iteration and continues at the beginning of the next iteration.
int i;
for (i = 0; i < 10; i++)
{
  if (i == 2) continue; /* start next iteration */
  else if (i == 5) break; /* end loop */
  printf("%d", i); /* "0134" */
}

Goto Statement

A third jump statement that may be useful to know of is goto, which performs an unconditional jump to a specified label within the same function. This instruction is generally never used since it tends to make the flow of execution difficult to follow.
goto myLabel; /* jump to label */
/* ... */
myLabel: /* label declaration */