Page 76 - Introduction to Programming with Java: A Problem Solving Approach
P. 76
42 Chapter 2 Algorithms and Design
set continueto“y”
while continue equals “y”
set biggest to 1
print “Enter a number (negative to quit): ” input num
while num is greater than or equal to 0
if num is greater than biggest set biggest to value of num
print “Enter a number (negative to quit): ”
input num
if biggest is not equal to 1
print “The Biggest number entered was ” biggest print “Play another game? (y/n): ”
input continue
⎫ ⎪ ⎪ ⎪ ⎪ ⎪
⎫ ⎪
⎪ ⎪ ⎭⎪ ⎪ ⎪ ⎪ ⎭
⎪ inner ⎪⎬ ⎬⎪ loop ⎪
outer loop
Figure 2.13 Algorithm that plays multiple games of “Find the largest number”
You’ll see that the if statement checks the new number to see if it is bigger than the previous biggest number, and if it is bigger, then the new number is assigned into the biggest variable. That assignment crowns the new number as the new champion.
Note the set biggest to 1 initialization at the top of the outer loop. What’s the point Apago PDF Enhancer
Use an extreme case.
of initializing biggest to 1? Initialize the champion variable (biggest) with a starting value that will automatically lose the first time a new number is compared to it. You know that 1 will lose to the first number in a find-the-largest-number contest because the contests are
limited to nonnegative numbers and nonnegative numbers are always greater than 1. After the first input re- places biggest’s 1 initial value, subsequent inputs may or may not replace biggest’s value, depending on the size of the input number and the size of biggest.
2.11 Tracing
Dig into details.
Up until now we have focused on design. Now let’s look at analysis—breaking up of a whole into its parts. In the present context, that means going through the details of an already-existing algorithm. The analysis technique we’ll use is called tracing, where you
essentially pretend that you’re the computer. You step through an algorithm (or a program) line by line and carefully record everything that happens. In the early parts of this book we’ll use tracing to illustrate pro- gramming details we’re trying to explain. Tracing gives you a way to make sure that you really understand newly learned programming mechanisms. Tracing also gives you a way to verify whether an existing algo- rithm or Java code is correct, or whether it has bugs.
What are bugs? One of the early digital computers, the Harvard Mark II, used mechanical relays rather than transistors, and programmers programmed by changing electrical connections. As the story goes,2 even though all the electrical connections were right, the computer kept making a mistake. Finally the programmer discovered a moth squeezed between the contacts of one of the relays. Apparently, the moth had been squashed when the relay contacts closed, and the moth’s dead body was interrupting the proper flow of electricity
2 http://www.faqs.org/docs/jargon/B/bug.html