Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple do while loop using while(true);

Tags:

c

loops

do-while

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

like image 585
Dev Avatar asked Feb 18 '13 10:02

Dev


People also ask

Do while loop while true?

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.

What is while and do while loop?

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.

What is a true condition in a while 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 .


1 Answers

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.

like image 178
Sargam Modak Avatar answered Sep 29 '22 13:09

Sargam Modak