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

                36 Chapter 2 Algorithms and Design 2.8 Loops
We’ve now discussed two of the three structures in Figure 2.5—sequential structures and conditional struc- tures. Let’s now discuss the third structure—looping structures. Looping structures repeat the execution of a particular sequence of statements. If you need to execute a block of code many times, you could, of course, repeatedly write the code wherever you need it. However, that leads to redundancy, which is something you want to avoid in a computer program, because it opens the door to inconsistency. It’s better to write the code once and then reuse it. The simplest way to reuse a block of code is to go back up to before where that block starts, and run through it again. That’s called a loop. Every loop has a condition that determines how many times to repeat the loop. Think of driving through western Kansas and seeing a sign for “Prairie Dog Town.” Your kids demand that you take the prairie-dog drive-through tour. The decision about how many times to repeat the tour parallels the condition in a loop statement.
A Simple Example
Suppose you want to print “Happy birthday!” 100 times. Rather than writing 100 print “Happy birthday!” statements, wouldn’t it be better to use a loop? Figure 2.9 presents a solution to the Happy birthday algo- rithm in the form of a flowchart with a loop. The flowchart implements the looping logic with an arrow that goesfrom“setcounttocount 􏰀 1”backuptothe“countlessthanorequalto100?”condition.
  Figure 2.9
Flowchart for our Happy Birthday algorithm
set count to 1
Apago PDF Enhancer
 count
less than or equal to 100?
  no
 print “Happy birthday”
 set count to count + 1
In a loop you’ll often use a count variable that keeps track of the number of times the loop has repeated. You can either count up or count down. The Happy birthday flowchart counts up.
In the last operation, instead of saying “set count to count + 1,” you could have said something like “increment count by one.” We chose to use this “set” wording to reinforce a way of thinking that corresponds to how a computer updates a variable’s value. Go back and review the thinking associated with Figure 2.3. First the computer performs a mathematical calculation using existing variable values. In Figure 2.3, the calculation involved two variables, length and width, that were different from the variable be- ing updated, rectangleArea. In Figure 2.9 the calculation involves the variable being updated, count. After the computer completes the calculation, it assigns the result of the calculation to the variable being
yes



















































































   68   69   70   71   72