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 {
while test the condition before executing statements in the while loop.
do while test the condition after having executed statement inside the loop.
Probably wdlen
starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.
In the second case the loop body is executed before the wdlen<2
condition is checked for the first time, so the printf
/scanf
is executed at least once.
While:
entry control loop
condition is checked before loop execution
never execute loop if condition is false
there is no semicolon at the end of while statement
Do-while:
exit control loop
condition is checked at the end of loop
executes false condition at least once since condition is checked later
there is semicolon at the end of while statement.
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.
The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check
The example is as such:
Program 1:
int a=10;
do{
System.out.println(a);
}
while(a<10);
//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop
Program 2:
int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit
output Program 1:
10
output Program 2:
[nothing is printed]
note:
output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.
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.