In real projects, where can we use do-while loop? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 7

In real projects, where can we use do-while loop?

I am wondering where we can use do-while loop in real projects/applications because I thought it executes a false part but only once. But which part of the project is it? Can you give me example?

14th Sep 2018, 2:48 PM
Email Not Activated
6 Antworten
+ 5
Schindlabua I know the use of it. What I mean is where can we use it in real projects?
14th Sep 2018, 3:11 PM
Email Not Activated
+ 5
For example to read input from the user: do { x = input("Please enter a valid command"); } while ( x not in ["help", "start", "exit"] ); To be honest I pretty much never use it, maye once or twice a year. The problem I have is that if you want to do something with `x` in the loop, you need to check it's validity twice. Like do { x = do_thing(); if( !is_valid(x) ) break; //do more things with x } while ( is_valid(x) ); Ugly. The alternative is a normal while loop, but there you have to do_thing() twice: x = do_thing(); while( is_valid(x) ){ // do more things with x x = do_thing(); } Pick your poison. Anyway do/while is mostly useful for one-line loops I find. I hear it's more common in low-level languages like C.
14th Sep 2018, 3:20 PM
Schindlabua
Schindlabua - avatar
+ 3
var x; do { x = do_stuff(); } while ( x != "we are done" ); That's the common use case I think, where you have to do_stuff() once, otherwise you have nothing to check in the while condition.
14th Sep 2018, 3:05 PM
Schindlabua
Schindlabua - avatar
+ 3
Best example : Suppose you have a function that calls an ambulance(or police). Whenever this function is executed output must be true. In this case we should first do the functionality then check for conditions like whether the phone number from where it gets call is a valid/invalid.
15th Sep 2018, 9:28 PM
Jai Verma
Jai Verma - avatar
+ 2
In Python there isn't a 'do while'. So if for example you want to run a loop until the user stops to input anything, you first have to define an initial 'something' although you don't need it: data = True while data: data = input() (Or you do it with while True, if and break.) So when I started c++ I just thought: "Hm, nice ... " do { cin >> data; } while ...
14th Sep 2018, 7:20 PM
HonFu
HonFu - avatar
+ 1
Imagine you have a multiplayer game, where the players play alternately. But when you destroy one of your opponent units, it's your turn again. So when it's your turn you always play at least once. do{ chooseYourMove(); } while(hasDestroyedUnitLastMove());
14th Sep 2018, 3:04 PM
Jonas