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

前端 未结 16 1143
爱一瞬间的悲伤
爱一瞬间的悲伤 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:28

    do {
        printf("Word length... ");
        scanf("%d", &wdlen);
    } while(wdlen<2);
    

    A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Therefore it'll print the string and call scanf, thus updating the wdlen variable.

    while(wdlen<2){
        printf("Word length... ");
        scanf("%d", &wdlen);
    } 
    

    As for the while loop, it evaluates the loop condition BEFORE the loop body is executed. wdlen probably starts off as more than 2 in your code that's why you never reach the loop body.

提交回复
热议问题