C语言do-while循环
do while循环是经过测试的循环。使用do-while循环,我们可以重复执行语句的多个部分。 do-while循环主要用于我们需要至少执行一次循环的情况。 do-while循环主要用于菜单驱动程序,其终止条件取决于最终用户。
do while循环语法
C语言的do-while循环如下:
do{
//code to be executed
}while(condition);
输出
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print lidihuo\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("lidihuo");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
输出
1. Print Hello
2. Print lidihuo
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print lidihuo
3. Exit
2
lidihuo
do you want to enter more?
n
do while循环的流程图
在示例中执行
给出了简单的c语言程序do while循环,用于打印1的表。
#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}
输出
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
输出
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
不定式的while循环
如果我们传递任何非零值作为条件表达式,则do-while循环将无限次运行。
do{
//statement
}while(1);