Why it is necessary to avoid infinite loop in program design?
It is not necessary to avoid infinite loops. You are perhaps
confusing infinite loops with endless loops which are to be avoided
at all costs. An endless loop is an infinite loop that has no
reachable exit condition; the loop will iterate until we forcibly
terminate the program.
We use the the term infinite loop in the sense that it is
impossible to measure or calculate when the exit point will be hit.
the following are all examples of infinite loops in their simplest
form:
for (;;) {
// ...
}
while (true) { // ... }
do while (true) {
// ...
}
endless:
// ...
goto endless;
The conditional expressions in each of these loops can never be
false thus we cannot easily determine when these loops will exit.
We typically use infinite loops when there are many exit conditions
to consider and it is either impractical or inefficient to evaluate
all of those conditions via the controlling expression alone. We
take it as read the exit conditions are contained within the body
of the loop.
If the body of the loop has no reachable exit condition then it
becomes an endless loop. It is the programmer's responsibility to
ensure that all infinite loops can exit at some point.