1.do-while循环的语法
我们知道C语言有三大结构,顺序、选择、循环。我们可以使用while循环、for循环、do-while循环实现循环结构。之前的博客中提及到了前两者的技术实现。可以参考:
C语言(11)------------->while循环 CSDN
C语言(12)--------->for循环 CSDN
那do-while循环的语法是怎样的呢?
do
{
控制语句;
}while(判断表达式);
我们看一个例子
打印1-10的数字:
参考代码:
#include <stdio.h>int main()
{int a = 1;do{printf("%d ",a);a++;} while (a<=10);return 0;
}
在VS2019中的运行结果:
2.do-while循环的练习
输入一个数字,判断它是几位数。
例如:
输入:0
输出:1
参考代码:
#include <stdio.h>int main()
{int num = 0;int count = 0;scanf("%d",&num);do{count++;num = num / 10;} while (num);printf("count=%d\n",count);return 0;
}
在VS2019中的运行结果:
仔细查看此处的代码,会发现它避免了输入为0输出也为0。这是因为do-while循环至少执行一次循环。
3.do-while循环的break和continue
while循环和for循环的break和continue问题我在之前的博客中有所提及:
C语言番外篇(3)------------>break、continue CSDN
这篇文章提及的是do-while循环的break和continue问题。
(1)break
参考代码:
#include <stdio.h>int main()
{int a = 1;do{if (5 == a)break;printf("%d ",a);a++;} while (a<=10);return 0;
}
在VS2019中的运行结果:
(2)continue
参考代码:
#include <stdio.h>int main()
{int a = 1;do{if (5 == a)continue;printf("%d ", a);a++;} while (a <= 10);return 0;
}
在VS2019中的运行结果: