C语言教程 - while循环

while循环与for循环很像,但功能更少。


Tutorial

while循环与for循环很像,但功能更少。只要条件为真while循环会一直执行代码块。例如下面的代码会执行十次:

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

while循环会一直执行只要判断为真(即非零值):

while (1) {
   /* 做某事 */
}

循环指令

在C语言中有两个重要的循环指令在所有的循环类型起作用——breakcontinue指令。

在循环10次后break指令停止循环,尽管从条件来这个while循环判断永远不会结束:

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

在下面的代码中,continue指令使printf命令被跳过,所以只有偶数被打印出来:

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

    /* 检查n是否为奇数 */
    if (n % 2 == 1) {
        /* 回到while代码块的开头 */
        continue;
    }

    /* 只有当n是偶数时,才能执行到这行代码 */
    printf("The number %d is even.\n", n);
}

Exercise

array变量是一个10个数字组成的序列。在while循环中,你必须写两个if判断,
它们以如下方式改变循环的流程(不改变printf命令):

  • 如果当前数字小于5,不打印。
  • 如果当前数字大于10,不打印并停止循环。

请注意:如果不推进迭代器变量i并使用continue指令,你将陷入死循环。

Tutorial Code

#include <stdio.h>

int main() {
    int array[] = {1, 7, 4, 5, 9, 3, 5, 11, 6, 3, 4};
    int i = 0;

    while (i < 10) {
        /* 在这里写你的代码 */

        printf("%d\n", array[i]);
        i++;
    }

    return 0;
}

Expected Output

7
5
9
5

Solution

#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;
}