loops - 所有while循环都可以转换为for循环吗?
问题描述
早些时候,我认为在使用链表时我们不能使用 for 循环......但后来
for(current = head; current != NULL; current = current->next)
这行让我思考。是否所有的 while 循环都可以转换为 for 循环,尤其是当有多个条件时?
解决方案
是的,任何可以写在 while 循环中的东西都可以用 for 循环来表示。它们都是入口控制循环,这意味着首先它们检查条件,然后执行主体。
为了使循环正常运行,我们至少需要一件事,即条件和最多三件事:
- 循环变量的初始化(如有必要)
- 条件(必要)
- 修改循环变量(如果循环变量已初始化)
现在我将展示一个带有 while 和 for 循环的简单代码块:
-> 打印从 1 到 100 的所有自然数。
使用 While 循环
int i=1; //Initialization of looping variable
while(i<=100) //Condition check
{
cout<<i;
i++; //Increment (Modification of looping variable)
}
使用 For 循环
方法一:
for(int i=1;i<=100;i++)
//Here the first part to the for is initialization of looping variable.
// Second part is the Condition
// Third part is the increment
{
cout<<i;
}
方法二:
int i=1;//Initializing the loop variable
for(;i<=100;)//Condition
{
cout<<i;
i++;//Increment
}
我给出了这 2 种方法来编写 For 循环,以表明 while 和 for 循环都只能与condition
. 如果我们有足够的能力以我们需要的格式重写代码,那么两者将以完全相同的方式运行。
推荐阅读
- azure - 达到每日上限后如何重新启动 Application Insights 日志记录
- android - 如何以编程方式检测 Mi 设备中的全屏手势模式
- swift - 如何将标准模型类/结构变成可观察的属性?
- arrays - 在 Spark 分区中获取前 n 个已排序元素的有效方法
- excel - Excel 正在随机填充计算单元格
- node.js - 项目部署到真实主机后,电子邮件停止发送
- amazon-web-services - 在 AWS 建议上部署 Node Express
- c# - 填充 Dts 变量时出现问题
- android - 如何在我的数据类模型中将字符串从 Retrofit 转换为自定义对象?
- spring-boot - 根据 Spring Boot 上的属性实例化服务