while循环的使用


前言

while 循环是 C 语言中一种基本的控制结构,用于重复执行一段代码,直到给定条件不再满足。while 循环的语法如下:

一、语法

while (condition) {
    // 循环体
}
  • condition 是一个布尔表达式,只有当其值为真(非零)时,循环体才会被执行
  • 循环体可以包含任意数量的语句

二、使用场景

while 循环通常用于以下情况:

  1. 未知迭代次数:当循环的迭代次数在开始时未知,直到满足某个条件。
  2. 读取输入:例如,读取用户输入直到用户输入特定的结束条件。

三、示例

以下是一些使用 while 循环的示例:

示例 1:基本使用

#include <stdio.h>

int main() {
    int count = 0;

    while (count < 5) {
        printf("Count is: %d\n", count);
        count++; // 增加计数
    }

    return 0;
}

输出:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

示例 2:读取用户输入

#include <stdio.h>

int main() {
    int number;
    
    printf("Enter numbers (0 to stop):\n");
    
    while (1) { // 无限循环
        scanf("%d", &number);
        if (number == 0) {
            break; // 条件满足时退出循环
        }
        printf("You entered: %d\n", number);
    }

    return 0;
}

输出:

Enter numbers (0 to stop):
5
You entered: 5
3
You entered: 3
0

示例3:使用 continue

#include <stdio.h>    

int main() {    
    int count = 0;    

    while (count < 10) {    
        count++;    
        if (count % 2 == 0) {    
            continue; // 跳过偶数    
        }
        printf("%d is odd\n", count);    
    }

    return 0;    
}

输出:

1 is odd
3 is odd
5 is odd
7 is odd
9 is odd

四、注意事项

  1. 条件必须变化:确保在循环体内有逻辑使得条件最终会变为假,否则会导致无限循环。
  2. 使用 break 语句:可以在循环体内使用 break 语句提前退出循环。
  3. 使用 continue 语句:可以使用 continue 语句跳过当前迭代的剩余部分,直接开始下一次迭代。

总结

while 循环是一种灵活且强大的控制结构,适用于需要根据条件重复执行代码的场景。理解和正确使用 while 循环是掌握 C 语言编程的重要基础。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值