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. For example, the following code will execute exactly ten times:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | include <stdio.h> int main() { int array[] = {1, 7, 4, 5, 9, 3, 5, 11, 6, 3, 4}; int i = 0; while (i < 10) { /* your code goes here */ printf("%d\n", array[i]); i++; } return 0; |
There are two important loop directives that are used in conjunction with all loop types in C - the break and continue directives.
The break directive halts a loop after ten loops, even though the while loop never finishes:
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main() { int n = 0; while (1) { n++; printf("%d\n",n); if (n == 10) { break; } } return 0; |
In the following code, the continue directive causes the printf command to be skipped, so that only even numbers are printed out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int main() { 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); } return 0; } |
0 Comment to "While Loop"
Post a Comment