While loops while 循环
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 remains true(保持真). For example, the following code will execute(执行) exactly ten times:
int n = 0;
while (n < 10) {n++;
}
While loops can also execute infinitely(无限地) if a condition is given which always evaluates as(评估为,认为) true (non-zero):
while (1) {/* do something */
}
Loop directives 循环指令
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:
int n = 0;
while (1) {n++;if (n == 10) {break;}
}
In the following code, 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++;/* 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);
}
Exercise
The array
variable consists of(由...组成) a sequence of ten numbers. Inside the while loop, you must write two if
conditions, which change the flow(流程) of the loop in the following manner(以以下方式) (without changing the printf
command):
-
If the current number which is about to printed is less than 5, don't print it.
-
If the current number which is about to printed is greater than 10, don't print it and stop the loop.
Notice that if you do not advance the iterator variable i(迭代变量i)
and use the continue
derivative, you will get stuck in(陷入) an infinite loop(无限循环中,死循环).
原:
#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;
}
改:
#include <stdio.h>int main() {int array[] = {1, 7, 4, 5, 9, 3, 5, 11, 6, 3, 4};int i = 0;while (i < 10) {if(array[i] < 5){i++;continue;}if(array[i] > 10){break;}printf("%d\n", array[i]);i++;}return 0;
}
#By yangbo 2020/04