首页 > 解决方案 > 所有while循环都可以转换为for循环吗?

问题描述

早些时候,我认为在使用链表时我们不能使用 for 循环......但后来 for(current = head; current != NULL; current = current->next) 这行让我思考。是否所有的 while 循环都可以转换为 for 循环,尤其是当有多个条件时?

标签: loopslinked-listnavigation

解决方案


是的,任何可以写在 while 循环中的东西都可以用 for 循环来表示。它们都是入口控制循环,这意味着首先它们检查条件,然后执行主体。

为了使循环正常运行,我们至少需要一件事,即条件和最多三件事:

  1. 循环变量的初始化(如有必要)
  2. 条件(必要)
  3. 修改循环变量(如果循环变量已初始化)

现在我将展示一个带有 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. 如果我们有足够的能力以我们需要的格式重写代码,那么两者将以完全相同的方式运行。


推荐阅读