+ 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?
6 Antworten
+ 5
Schindlabua I know the use of it. What I mean is where can we use it in real projects?
+ 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.
+ 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.
+ 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.
+ 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 ...
+ 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());