Many times in the examples of C programs, I came across these kind of loops. What do these kind of loops really do?
do {
while (...) // Check some condition if it is true.
{
calculation 1
}
// Some new condition is checked.
} while(true);
What is the need of while(true);
Is it used for infinite looping? Can someone please explain what the above loop really does. I am new to C programming
The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
While loop checks the condition first and then executes the statement(s), whereas do while loop will execute the statement(s) at least once, then the condition is checked. While loop is entry controlled loop, whereas do while is exit controlled loop.
A Boolean condition is a condition that evaluates to either True or False . A while loop will always first check the condition before running. If the condition evaluates to True , then the loop will run the code within the loop's body and continue to run the code while the condition remains True .
These loops are used when one wants to loop forever and the breaking out condition from loop is not known. Certiain conditions are set inside the loop along with either break or return statements to come out of the loop. For example:
while(true){
//run this code
if(condition satisfies)
break; //return;
}
These loops are just like any other while loop with condition to stop the loop is in the body of the while loop otherwise it will run forever (which is never the intention of a part of the code until required so). It depends upon the logic of the programmer only what he/she wants to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With