What is the purpose of a do-while loop?

前端 未结 5 2078
说谎
说谎 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:35

    The biggest difference between while and do-while statement is, whether it is executed at least one time or not.

    while(false)
     printf("print!");
    

    with this statement, the program will never print the string. However,

    do{
        printf("print!");
    }while(false);
    

    with this statement, the program will print the string once.

    But many people don't recommend to use do-while statement--because it can be substituted with while statement. It doesn't mean that do-while statement is critically harmful, but it is rarely used.

    In fact, for loop is the most safe and recommended way because the programmer can handle the iteration number, loop conditions, and increasing variables easily. So if you don't have any specific reason that you have to use while loop, just use for loop.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2021-01-17 09:43

    Use do-while() construct when you have to get your task executed at least once even if condition fails. Use while() when you your task to be executed only on certain condition success.

    0 讨论(0)
  • 2021-01-17 09:52

    if you write the "loop" like so (without the do as in your question):

    int i=0;
    {
        System.out.println(i++);
    }while(i<10);
    

    it will just print out 0 (nothing more), and not loop 10 times.. so no, the loop won't be the same if the do isnt there.

    0 讨论(0)
  • 2021-01-17 09:53

    The difference is with "do-while" loop will be executed at least one time. With "while" loop with false condition the loop body will not be executed.

    0 讨论(0)
提交回复
热议问题