C语言中的while循环是一种预测试循环。通常情况下,while循环允许根据给定的布尔条件执行一部分代码多次。它可以看作是一个重复的if语句。while循环主要用于在不提前知道迭代次数的情况下使用。

C语言中while循环的语法如下:

while (condition) {
    //要执行的代码
}

C语言中while循环的示例

以下是一个打印1的乘法表的简单while循环程序:

#include <stdio.h>

int main() {
    int i = 1;
    
    while (i <= 10) {
        printf("%d \n", i);
        i++;
    }

    return 0;
}

输出:

1
2
3
4
5
6
7
8
9
10

使用while循环打印给定数字的乘法表的程序:

#include <stdio.h>

int main() {
    int i = 1, number = 0;
    
    printf("Enter a number: ");
    scanf("%d", &number);

    while (i <= 10) {
        printf("%d \n", (number * i));
        i++;
    }

    return 0;
}

输出:

Enter a number: 5
5
10
15
20
25
30
35
40
45
50

while循环的特点

  • 使用条件表达式来检查条件。在while循环内定义的语句将重复执行,直到给定的条件失败。
  • 如果条件返回0,则条件为真。如果条件返回非零数,则条件为假。
  • 在while循环中,条件表达式是必需的。
  • 可以在while循环中有多个条件表达式。
  • 如果循环体中只包含一个语句,则大括号是可选的。

无限循环的while循环

如果while循环中的表达式结果为非零值,则循环将无限运行。

while (1) {
    //语句
}

标签: c语言, c语言教程, c语言技术, c语言学习, c语言学习教程, c语言下载, c语言开发, c语言入门教程, c语言进阶教程, c语言高级教程, c语言面试题, c语言笔试题, c语言编程思想