5.6. Comparing loop constructs

[5.4] Compare loop constructs

In this section, I’ll discuss the differences and similarities between the following looping constructs: do-while, while, for, and enhanced for.

5.6.1. Comparing do-while and while loops

Both do-while and while loops execute a set of statements until their termination condition evaluates to false. The only difference between these two statements is that the do-while loop executes the code at least once, even if the condition evaluates to false. The do-while loop evaluates the termination condition after executing the statements, whereas the while loop evaluates the termination condition before executing its statements.

The forms taken by these statements are depicted in figure 5.20.

Figure 5.20. Comparing do-while and while loops

What do you think the output of the following code is?

The output of the preceding code is as follows:

12

What do you think the output of the following code is?

The output of the preceding code is as follows:

11

5.6.2. Comparing for and enhanced for loops

The regular for loop, although cumbersome to use, is much more powerful than the enhanced for loop (as mentioned in section 5.4.1):

  • The enhanced for loop can’t be used to initialize an array and modify its elements-.
  • The enhanced for loop can’t be used to delete the elements of a collection.
  • The enhanced for loop can’t be used to iterate over multiple collections or arrays in the same loop.

5.6.3. Comparing for and while loops

You should try to use a for loop when you know the number of iterations—for example, when you’re iterating through a collection or an array or when you’re executing a loop for a fixed number of times, say, to ping a server five times.

You should try to use a do-while or a while loop when you don’t know the number of iterations beforehand and when the number of iterations depends on a condition being true—for example, when accepting passport renewal applications from applicants until there are no more applicants. In this case, you’d be unaware of the number of applicants who have submitted their applications on a given day.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.70