+ 4

What is the point of do{} while()?

Surely all conditional statements should output only if the while statement is true. If the "do" always outputs once without any condition, what is its purpose? Can someone give a usage example please?

30th May 2018, 7:52 PM
Richard Owens
Richard Owens - avatar
6 Antworten
+ 2
The (small) difference is: In a while{} loop, the block may never be executed. In a do{}while loop, the block is always executed at least once. This can be useful, e.g. boolean repeat = true; do{ //do something //check some result repeat = need_to_try_again(); } while(repeat)
30th May 2018, 8:42 PM
ifl
ifl - avatar
+ 2
For instance in a text calculator. The user is asked whether he wants to go again. This can be put inside a do...while loop.
30th May 2018, 7:56 PM
Paul Grasser
Paul Grasser - avatar
+ 2
You ask user for an input, like a password, but it must be at least 6 characters long. Thus, you’ll have to ask him/her the password at least once, and then keep asking for it for as long as you don’t get a valid input. A do-while loop does the job.
31st May 2018, 12:09 AM
Pedro Demingos
Pedro Demingos - avatar
+ 2
do while is very important when you need to put validations on inputs of your program. i.e. repeatedly ask for the input until a valid input is given.
31st May 2018, 8:11 AM
KK Bhatt
KK Bhatt - avatar
0
Perfect. Thank you to both answers.
30th May 2018, 9:24 PM
Richard Owens
Richard Owens - avatar
0
the do-while loop is used when the statement within the loop must run atleast once. here's some example: 1.If u want to travel by your own vehicle(two wheeler or four wheeler),You should know how much petrol available in your vehicle and you know how much distance to travel (For loop  ---Know the initial condition and no of iterations) 2.If u want to travel in a FLIGHT, You should buy a ticket then only you are eligible to enter into the Flight. (While loop ---- First satisfy the condition then Proceed) 3.If u want to travel in BUS, You can board the bus then buy the ticket. (DO WHILE ---- Proceed first then checking)
6th Jun 2018, 6:52 PM
Rahul Kumar
Rahul Kumar - avatar