while(1) how it should be applied

please explain me why we use while(1) in programm

In case we aren’t sure when the loop should terminate (rarely happens)
or
there are too many conditions on the loop and its easier to break the loop when a condition gets false.

Also if u want only a part of ur code to be executed and not some other part depending on certain condition…
Basically you would prefer to break the loop when you encounter certain conditions within the loop rather than thinking of all the conditions at first and writing them at the top! (Kinda hard with lets say 5-6 conditions)

Eg.

x=0;

while(1){

y=x*x;

func1(y);

if(y>10){

break;

}

func2(y);

x++;

}

Now here you want that func2() shouldnt execute if y>10 but you do want func1() to execute for the first such value of y greater then 10! (16 in this case when x is 4)

Now this is kinda hard to code clearly in the while loop! Hope you understand! :smiley:

Although i must say its not a good practice and can always be avoided!

Hope this helps! :slight_smile:

while(1) condition basically generates an infinte loop.we must break from it to stop the loop.
it can be basically used when the condition for exiting from the loop depends upon the body of the loop itself or in cases where the conditions are not clear .But you can easily avoid it ,it is also not good practice,it can easily be replaced by the normal while loop ,because it can lead to error in your code.

@shivam1511
your while(1) code can also be replaced by normal while in the foll way.

x=0;y=0;

while(y<10)

{
y=x*x;

func1(y);

func2(y);

x++;

}

func1(y);

Oh thanx a lot! I dint know that! :stuck_out_tongue:

//