C Programming – Difference Between ‘while’ Loop and ‘do while’ Loop

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?

Best Answer

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.

Related Question