Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "while" loop and "do while" loop

Tags:

c

loops

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 {
        printf("Word length... ");
        scanf("%d", &wdlen);
    } while(wdlen<2);

This code works perfectly. It prints word length and tascans the input. But when I changed it to

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

It gives a blank screen. It do not work. So there is some functional difference between both loops. Can anybody explain it?

Is there any other difference in these two?

like image 244
narayanpatra Avatar asked Sep 02 '10 09:09

narayanpatra


4 Answers

The do while loop executes the content of the loop once before checking the condition of the while.

Whereas a while loop will check the condition first before executing the content.

In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.

like image 99
hydrogen Avatar answered Oct 22 '22 01:10

hydrogen


While : your condition is at the begin of the loop block, and makes possible to never enter the loop.

Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.

like image 25
Guillaume Lebourgeois Avatar answered Oct 22 '22 00:10

Guillaume Lebourgeois


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.

like image 3
Mahmoud Avatar answered Oct 22 '22 01:10

Mahmoud


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

like image 3
sriram Avatar answered Oct 22 '22 00:10

sriram