Example of a while loop that can't be written as a for loop

前端 未结 6 994
轮回少年
轮回少年 2021-01-18 08:10

I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?

Please provide an example.

6条回答
  •  囚心锁ツ
    2021-01-18 08:57

    While loop does not have as much flexibility as a for loop has and for loops are more readable than while loops. I would demonstrate my point with an example. A for loop can have form as:

    for(int i = 0, j = 0; i <= 10; i++, j++){
    // Perform your operations here.
    }
    

    A while loop cannot be used like the above for loop and today most modern languages allow a for each loop as well.

    In my opinion, I could be biased please forgive for that, one should not use while loop as long as it is possible to write the same code with for loop.

提交回复
热议问题