栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言入门(十)>>>循环 - 循环实例

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言入门(十)>>>循环 - 循环实例

文章目录
  • 循环实例
  • for循环
      • for语句的循环控制变量
      • 一些for循环的变种

循环实例
#include 
#include 

int main()
{
	int ch = 0;
	int ret = 0;
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);//输入密码,并存放在password数组中
	//缓冲区还剩余一个‘n’
	//读取一下‘n’
	while ((ch = getchar()) != 'n')
	{
		;
	}
	printf("请确认(Y/N):>");
	ret = getchar();
	if (ret == 'Y')
	{
		printf("确认成功n");
	}
	else
	{
		printf("放弃确认n");
	}
	return 0;
}
for循环

我们已经知道了while循环,但是为什么还有一个for循环呢?
首先来看for循环的语法:

语法

for(表达式1;表达式2;表达式3)
	循环语句:

表达式1为初始化部分,用于初始化循环变量的。
表达式2为条件判断部分,用于判断循环时候终止。
表达式3为调整部分,用于循环条件的调整。

实际的问题:
使用for循环在屏幕上打印1-10的数字。

#include 

int main()
{
	int i = 0;
	//初始化    判断    调整
	for (i = 1; i <= 10; i++)
	{
		printf("%d ", i);
	}
	return 0;
}

#include 


int main()
{
	int i = 0;
	//初始化    判断    调整
	for (i = 1; i <= 10; i++)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}
 1 2 3 4 6 7 8 9 10
#include 


int main()
{
	int i = 0;
	//初始化    判断    调整
	for (i = 1; i <= 10; i++)
	{
		if (i == 5)
			break;
		printf("%d ", i);
	}
	return 0;
}
1 2 3 4
for语句的循环控制变量

一些建议:
1、不可再for循环体内修改循环变量,防止for循环失去控制;
2、建议for语句的循环控制变量的取值采用“前闭后开区间”写法;

如下

#include 

int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	//10次循环
	//10次打印
	//10个元素
	for (i = 0; i < 10; i++)
	{
		printf("%d " , arr[i]);
	}
	return 0;
}
一些for循环的变种
//变种1
#include 

int main()
{
	for (;;)
	{
		printf("hehen");
	}
	return 0;
}

1、for循环的初始化、调整、判断 都可以省略
但是:
for循环的 判断部分 如果被省略,那判断条件就是:恒为正

2、如果不是非常熟练,建议大家不要随便省略

#include 

int main()
{
	int i = 0;
	int j = 0;
	for (; i < 10; i++)
	{
		for (; j < 10; j++)
		{
			printf("hehen");
		}
	}
	return 0;
}
hehe
hehe
hehe
hehe
hehe
hehe
hehe
hehe
hehe
hehe
//变种2
#include 

int main()
{
	int x, y;
	for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
	{
		printf("hehen");

	}
	return 0;
}
hehe
hehe

拓展

#include 

int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 0; i++, k++)
		k++;
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/887002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号