C语言入门(九)>>>循环 - while循环

文章目录


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。
按任意键关闭此窗口...

下一个章节再继续编写上述程序在项目中如何应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值