Difference between “while” loop and “do while” loop

前端 未结 16 1097
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 06:44

What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:

do {
                


        
相关标签:
16条回答
  • 2020-12-13 07:09

    do while in an exit control loop. while is an entry control loop.

    0 讨论(0)
  • 2020-12-13 07:09
    while(wdlen<2){
      ...
     }  
    

    If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.

    do{
     ...
    }while(wdlen<2)
    

    will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.

    0 讨论(0)
  • 2020-12-13 07:15

    while test the condition before executing statements within the while loop.

    do while test the condition after having executed statement within the loop.

    source: let us C

    0 讨论(0)
  • 2020-12-13 07:18

    The most important difference between while and do-while loop is that in do-while, the block of code is executed at least once, even though the condition given is false.

    To put it in a different way :

    • While- your condition is at the begin of the loop block, and makes possible to never enter the loop.
    • In While loop, the condition is first tested and then the block of code is executed if the test result is true.
    0 讨论(0)
  • 2020-12-13 07:19

    In WHILE first check the condition and then execute the program In DO-WHILE loop first execute the program at least one time then check the condition

    0 讨论(0)
  • 2020-12-13 07:20

    The difference is in when the condition gets evaluated. In a do..while loop, the condition is not evaluated until the end of each loop. That means that a do..while loop will always run at least once. In a while loop, the condition is evaluated at the start.

    Here I assume that wdlen is evaluating to false (i.e., it's bigger than 1) at the beginning of the while loop, so the while loop never runs. In the do..while loop, it isn't checked until the end of the first loop, so you get the result you expect.

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