Page 166 - Introduction to Programming with Java: A Problem Solving Approach
P. 166

                132 Chapter 4 Control Statements
4.11 Solving the Problem of Which Loop to Use
Now, let’s compare the various kinds of loops.
The do loop’s decision point is at the bottom of the loop. That’s in contrast to the while and for
loops, where the decision point is at the top of the loop. When the decision point is at the top of the loop, the decision stands out more and the code is therefore less prone to programming error.
        A toolkit needs more than one tool.
With programming, as in life, there are usually many different ways to accomplish the same thing. For example, for a problem that requires repetition, you can actually use any of the three loops to solve any repetition problem. Even though that’s the case, you should strive to make your programs elegant, and that means choosing the most appropri- ate loop even though any loop could be made to work.
   Flexibility makes programming fun if you like to be creative. But if you’re just starting out, that flex- ibility can lead to confusion. In Figure 4.16, we provide a table that attempts to alleviate some of that confu- sion. It suggests a way to choose an appropriate type of loop and how to get started with that loop’s code. We use angled brackets around text to indicate that the enclosed text is a description of code, not actual code. Thus, in using Figure 4.16’s do loop and while loop templates, you’ll need to replace <prompt—do it again (y/n?)> with actual code. For example, for a game program, you might use this actual code:
System.out.print("Do you want to play another game (y/n)? ");
response = stdIn.nextLine().charAt(0);
 Loop Type for loop:
do loop:
while loop:
When to Use
When you know, prior to the start of the loop, how many times you want to repeat the loop.
When you always need to do the repeated thing at least one time.
When looping is “event driven”; that is, you loop until some special condition changes.
Template
for (i=0; i<max; i++)
Apago PDF Enhancer
   {
}
<statements>
<statements>
<prompt - do it again (y/n)?> while (<response􏰅􏰅‘y’>);
do
{
}
<prompt - do it (y/n)?>
while (<response􏰅􏰅‘y’>) {
}
<statements>
<prompt - do it again (y/n)?>
Figure 4.16 Choosing the right loop and getting started with the loop’s code

































































   164   165   166   167   168