Do - while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Do - while loop

didnt really get how i the do-while loop helpful. whats better in it than the just while loop?

28th Nov 2016, 7:56 AM
ksnxnx
5 Answers
+ 2
A 'do while' loop will execute at least once because the condition is only checked at the end. do { wearSunglasses(); } while (sun is out); In this scenario you will put your sun glasses first then check if the sun is out. After the loop executes the first time the program should know if the sun is out or not and only put on the sunglasses if it is. A 'while' loop checks the condition first and will only execute the code between the curly braces if true. while (sun is out) { wearSunglasses(); } In this case if the sun is not out you will not wear your sunglasses. Hope that helps.
28th Nov 2016, 8:46 AM
Jacques Navarro
Jacques Navarro - avatar
+ 1
Do-while allows the code to be executed first, before the condition check on while.
28th Nov 2016, 8:47 AM
Felipe Cruz
Felipe Cruz - avatar
+ 1
When ever you want a piece of code to execute at least once regardless of the state of the condition. Imagine you work in a coffee shop and the owner wants you to sweep the floor every morning even if it's clean. do {sweepFloor(); } while (floor is dirty);
28th Nov 2016, 8:56 AM
Jacques Navarro
Jacques Navarro - avatar
0
ok. thanks.can i get an example on when is it useful?(the do while)
28th Nov 2016, 8:49 AM
ksnxnx
0
If you want your code to execute atleast once before checking the condition in the while() , you can use do { // code that runs at least once before checking the condition }while();
12th Dec 2016, 3:36 AM
network me
network me - avatar