spirito-buono
4/26/2018 - 11:35 AM

While loops

While loops are similar to for loops, but have less functionality. A while loop continues executing the while block as long as the condition in the while holds.

There are two important loop directives that are used in conjunction with all loop types in C - the break and continue directives.

the continue directive causes the printf command to be skipped, so that only even numbers are printed out.

int n = 0;
while (n < 10) {
    n++;
}

while (1) {
   /* do something */
}

int n = 0;
while (1) {
    n++;
    if (n == 10) {
        break;
    }
}

int n = 0;
while (n < 10) {
    n++;
}

int n = 0;
while (n < 10) {
    n++;

    /* check that n is odd */
    if (n % 2 == 1) {
        /* go back to the start of the while block */
        continue;
    }

    /* we reach this code only if n is even */
    printf("The number %d is even.\n", n);
}