C语言教程:do-while循环

2018-10-0608:21:24编程语言入门到精通Comments3,533 views字数 1101阅读模式

要执行程序或代码的一部分几次或多次,我们可以使用C语言do-while循环。 在dowhile之间给出的代码将被执行,直到条件(condition)成为true文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do-while迭代代码,直到条件(condition)为false。 这里,条件(condition)是在代码之后给出的。所以循环体至少一次,而不管条件(condition)求值是真还是假。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

如果你希望代码必须至少执行一次,那使用do-while循环是一个不错的选择。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

C语言do-while循环的语法如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do{  
    //code to be executed  
}while(condition);

do-while循环中,语句在条件之前给出,所以语句或代码将至少有一次执行。换句话说,我们可以说do-while循环执行语句一次或多次。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

如果你希望至少执行一次代码,使用do-while循环是最好不过的选择。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do-while循环语法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

C语言do-while循环的语法如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do{  
    //code to be executed  
}while(condition);
C

do-while循环的流程图文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

C语言教程:do-while循环文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do-while循环的例子文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

下面给出了C语言的简单程序,while循环来打印连续的数据。创建一个源文件:do-while-example.c,其代码如下所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

#include <stdio.h>    
#include <conio.h>    
void main() {
    int i = 1, number = 0;
    printf("Enter a number: ");
    scanf("%d", &number);
    do {
        printf("%d \n", (i));
        i++;
    } while (i <= number);
}
C

执行上面代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

Enter a number: 12
1
2
3
4
5
6
7
8
9
10
11
12
请按任意键继续. . .
Shell

使用do while循环打印给定数字表的程序文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

实现一个输入数的倍数打印,创建一个源文件:do-while-print-table.c,参考以下代码的实现 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

#include <stdio.h>    
#include <conio.h>    
void main() {
    int i = 1, number = 0;
    printf("Enter a number: ");
    scanf("%d", &number);
    do {
        printf("%d \n", (number*i));
        i++;
    } while (i <= 10);
}
C

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

Enter a number: 8
8
16
24
32
40
48
56
64
72
80
Shell

无限do-while循环文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

如果在do while循环中使用条件表达式的值1,则它将运行无限次数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html

do{  
   // 要执行的语句
}while(1);
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6397.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/6397.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定