Difference while vs do-while loop
In this article, we will learn about the difference between while and do-while loop.
Basically while and do-while are used to execute program in loop but they have their own way of executing the loop. Lets see below the difference in operation of while and do-while with proper examples.
Execution process in while loop
While loop checks the condition at the beginning of the loop.
If the condition is found to be true then only the statement inside the loop's body gets executed.
Lets understand the above statements with an example on while loop:
int num = 8;
while(num<5){
//Inside while loop
System.out.print("condition is true");
num++;
}
How the above code would be executed?
-
int variable num is assigned value 8
-
Now condition num<5 is tested for while loop. In our case, num = 8 so 8<5 is false.
-
So the control will not enter inside the body of while loop and the loop terminates.
[Assign num =4, now 4<5, the statements within while loop will execute]
Thus we see while loop tests the condition at the beginning when while loop begins.
Execution process in do-while loop
do while loop checks the condition at the end of the loop.
As the condition is tested at end of the loop so the body inside loop gets executed at least once, even in case the condition is found to be false.
Lets understand above statements with an example of do-while loop:
int num = 8;
do{
//Inside do while loop
System.out.print("condition is true");
num++;
}while(num<5);
How the above code would be executed?
-
int variable num is assigned value 8
-
Since there is no condition test and a statement do indicates to go inside loop. Thus control moves inside body of do-while.
-
Statement "condition is true" is printed on console.
-
Value of num++ occurs.
-
Now condition num<5 will be tested. Now num = 9 and 9<5 is false. So the loop terminates and control passes outside do-while loop.
Thus we see that even when the condition is false, the do-while loop body is executed atleast once.
Conclusion
If you need a application, where you want to execute your code at least once even if condition is false use do-while. This mostly used to create menu driven java programs.
And if you are strict with condition check and don't want any execution for false outcome go for while loop
Use of semi-colon (;)
Another difference can be observed in syntax of while and do-while.
do-while loop ends with a semi-colon (;) but while loop doesn't use semi-colon (;) at all.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :
Published Date :
Jul 05,2020