An infinite loop is one that will execute forever unless a statement, such as the break statement is used to force its termination. Infinite loops are quite useful to avoid an awkward logical condition for a loop.
An infinite while loop should use the true
keyword as its logical expression:
while (true) { // body }
A for loop could be as simple as using nulls for each part of the for statement:
for (;;) { // body }
A loop that never terminates would not normally be of value for most programs since most programs should eventually terminate. However, most infinite loops are designed to terminate using the break statement, shown as follows:
while (true) { // first part if(someCondition) { break; } // last part }
This technique is fairly common and is used to simplify the logic of a program. Consider the need to read in an age and terminate when the age is negative. It is necessary to assign a non-negative value to age to ensure that the loop executes at least...