As you all probably know, do loops
execute at least once, even if the statement is false — while the while loop
would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
As you all probably know, do loops
execute at least once, even if the statement is false — while the while loop
would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
They're basically useful when you want something to happen at least once, and maybe more.
The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:
lock table
do {
id = generate random id
} while(id exists)
insert into db with the generated id
unlock table
Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).