文章目录
while循环
我们已经掌握了if语句
if(条件)
语句;
当条件满足的情况下,if语句后的语句执行,否则不执行,但是这个语句只会执行一次。
但是我们发生生活中很多的实际的例子是:同一件事情我们要完成很多次。
C语言给我们引入了:while语句,可以实现循环。
//while 语法结构
while(表达式)
循环语句
#include <stdio.h>
#include <string.h>
int main()
{
int i = 1;
while (i<=10)
{
printf("%d ", i);
i++;
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
#include <string.h>
int main()
{
int i = 1;
while (i<=10)
{
if (i == 5)
break;
printf("%d ", i);
i++;
}
return 0;
}
1 2 3 4
总结:break在while循环中的作用:
在循环中只要遇到break,就停止后期的所有的循环,直接终止循环。所以:while中的break是用于永久终止循环的。
#include <stdio.h>
#include <string.h>
int main()
{
int i = 1;
while (i<=10)
{
if (i == 5)
continue;
printf("%d ", i);
i++;
}
return 0;
}
1 2 3 4 _(闪烁)
总结:continue在while循环中的作用:
continue是用于终止本次循环的,也就是本次循环中continue后面的代码不会再执行,而是直接跳转到while语句的判断部分,进行下一次循环的入口判断。
拓展:
#include <stdio.h>
#include <string.h>
int main()
{
int ch = getchar();
putchar(ch);
printf("%c\n", ch);
return 0;
}
r
rr
#include <stdio.h>
#include <string.h>
int main()
{
int ch = 0;
//CTRL + Z 会获取EOF
//EOF - end of file -> -1
while ((ch = getchar()) != EOF)
{
putchar(ch);
}
}
sfds
sfds
fsdfs
fsdfs
sdfsdf
sdfsdf
^Z
C:\Users\Administrator\Desktop\VS code\test_05_01\Debug\test_05_01.exe (进程 12116)已退出,返回代码为: 0。
按任意键关闭此窗口...
下一个章节再继续编写上述程序在项目中如何应用