What is the purpose of a do-while loop?

前端 未结 5 2075
说谎
说谎 2021-01-17 08:59

I know what do does, and how it cooperates with the while loop, but won\'t a while loop code be the same, whether or not the do is there?

5条回答
  •  醉梦人生
    2021-01-17 09:38

    Consider the following:

    while(condition){
       myFunction();
    }
    

    and

    do{
       myFunction();
    }while(condition);
    

    The second form executes myFunction() at least once then checks the condition! To do so with a while loop you've to write:

    myFunction();
    
    while(condition){
       myFunction();
    }
    

提交回复
热议问题