Chapter 06
Chapter 06
Chapter 06
do{
<s E a t e m e n t s >
] while (<condition>);
The condition of a loop is used to determine when the loop should stop
executing.A while continuesuntil its condition is false.What happens,
though, if the condition never becomesfalse? The result is an infinite
loop-one which continues forever. For example,the following generates
an infinite loop. Can you seewhy?
int num = -1;
while (nurn < 0) {
num = -1;
]
The code causesthe application to simply stop responding or just "hartg."
When this happens,closethe output window to end the application. Note
that some compilers may require a different procedure to end an infinite
loop.
Syntax errors are a common causeof infinite loops. For example, a
semicolonafter the condition causesthe statementto check the condition,
do nothing, check the condition, do nothing, and on and on:
while (num < 0); { //an infinite loop here--added semicolon
num += 1;
]
Another exampleof a syntax error that can lead to an infinite loop is
omitting the curly braces:
while (nun < 0) //an infinite loop here--no braces
System.out.print("Enter a value: ");
num = input.nextlnt0;
In this case, only the first statement is executed &nd nun is never assigned
the input. Although properly done, the indentation makes it difficult to
find the syntax error.
A logic error can also lead to an infinite loop condition. For example, in
the code below nun is initialized to 1 and never decremented to a number
less than 0 in the loop, making the condition of the loop structure always
true:
int nun = 1;
do{
num += 1;
] while (num >= 0);
In this case, the loop isn't infinite because numis eventually assigned a
overtbw number so large that an overflow results. An oaerflow occurs when there
are not enough bits to store a number. This may generate a run-time error
or, in the case of the code above, actually cause the condition to become
false. An overflow changes the sign of the number stored.
The AverageValue
applicationis basedon the pseudocode:
Promnt rrser for a value
while (va1ue != 0)
count value
add value to sum of values
pronpt user for another value
Display average of values (sum/count)
/* AverageValue application. */
int nunValues = 0;
int sum0fValues =0;
. 1 ^ , ], " 1- - - , ^ .
Scanner input = n e w S c a n n e r ( S y s t e m .i n ) ;
newValue = input.nextlnt0;
while (newValue != SENTINEL) {
nunValues += 1;
sum0fValues += newValue;
r r \ .
System.out.print("Enter a value(" + SENTINEL + " F ^
L v
^ . . a F \ .
Y q 4 s / . / |
newValue = input.nextlnt0;
]
input. close ();
Createa NumbersSum application that prompts the user for a number and then displays the numbers 1
through the number entered,each on a separateline. Below the numbers, the sum is displayed.
applicationthat prompts the user for a set of scoresand then calculatesthe percent-
Createa PercentPassing
ageof scoresabove70%.The user should have the option to enter as many scoresas needed.(Hint: Use an
if statementand anothercounter.)
loop control variable The following statement uses a counter to control the iterations of a for
statement. The counter i is the loop control oariable.When i is greater than
10,looping terminates:
T I P C o u n t e rv a r i a b l e si n a for (int i = l-; i <= 10; i++) {
f o r l o o p a r e o f t e n n a m e di , System. out. println (i) ;
j, or k.
]
Note that the counter is declared in the initialization of the for statement
scope (i"t i = 1). With a declaration in this location, the scopeof the counter
is from the initialization to the closing curly brace of the for statement.
The application will not recognize the variable outside of that statement.
programming style Declaring variables so that their scope is limited to where they are needed
is good programming style because it produces cleaner code and helps
eliminate the possibility of errors.
The statement above uses the ++ operator in the increment part of the
increment operator for statement (i++). The ++ operator is called the increment operatorbecause
it increases the value of a variable by 1. The ++ operator is a good choice
in the increment of a for statement because the effect is to increase the
operand by 1. However, ++ should not be used within an expression, such
ExpressionsUsing++ as i++ <= 1-0,because the value returned by the operator is used in the
or -- expression, not the final value of the operand.
lf the ++ or -- operator Any combination of components can be left out of a for statement. This
appearsbeforethe operand, can be useful when a counter is declared and initialized outside the state-
it is calledprefix(i.e.++i). An
ment, as in the following code:
operatorafterthe operandis
calledpostfix(i.e.i++). Either rnc num;
o p e r a t o rl o c a t i o nh a s t h e System.out.print("Enter the starting number: ");
sameeffecton the final varue nuro = input.nextlnt0;
o f t h e o p e r a n d .H o w e v e r , for (; nun <= l-0; num++) {
i n a n e x p r e s s i o nt ,h e p r e f i x qvcf6h ^,,f hri.f1. 1."-l .
Createan OddSum application that prompts the user for a number and then sums the odd numbers from 1
to the number entered.
T I F I o b u g "i s a n e r r o ri n a The source of bugs, which are often logic errors, can be hard to deter-
proSram. mine without tools for debugging an application. Debugglngis the process
of getting an applicationto work correctly.One tool included with many
compilers is called a debugger.
E
6 L] 7
I
s
s s 1!
When run, the code above displays the following output, which can be
compared to the values expected. Note the similarity to a variable trace:
commenting out code Commenting out statementscan be an effective way to locate a bug
through processof elimination. Typically the / / charactersare easiestto
type at the beginning of a statementto 'tomment it out."
Using paper and pencil, createa variabletracefor the following code,tracing the valuesof nun1,num2,
i, and
any output:
int numl- = 0;
int num2 = 0;
for (int i = 0; i <= 4; i++) {
nurnl=ixi;
num2 += numl-:
Svsfem nr)j- nrintlnuml + ");
]
System. out. println ( n u m 2) ;
inf nLrrcal.ararL.
int rnid;
Scanner input = new Scanner(System.in);
/* determinemiddle of phrase */
phraselengtfi
= phrase. length() ;
mid=phraseLength/2;
heIIo
Createan AccountSetupapplicationthat prompts the user for a user name and a password.The application
should prompt the user until a passwordwith at leasteight charactersis entered.The user name and pass-
word should be convertedto all lowercaselettersand then an appropriatemessagedisplayed.Application
output should look similar to:
Methods
equals(String str)
Chapter6 LoctpStructures
and Strings
System. out.print ( "Enter a w o r d . : " ) ;
worcll- = input.nextline 0 ;
System. out. print { "Enter a second woril:
woril2 = input.nextline0;
'i nnrrt n'l aea / I '
if (wordl.cornpareTolgnoreCase(word2) == 0) {
System.out.println("Worils are equal.");
] else if (worill.compareTolgnoreCase(word2) < 0) {
Systern.out.println("In alphabeticaf order: " + r+ord1
+"u+worcl2);
) else {
System.out.prj-ntln("In alphabetical orcler: + word2
+u"+wordl);
]
]
i
AlphaOrder produces output similar to the following:
Createa FormalGreeting application that prompts the user for his or her name, including title. The applica-
tion should display "Hello, sir." if the string startswith I'1r.,"Hello, mahm." if the string startswith u=.,ur=.,
or Miss,and "Hello, name."otherwisewhere nameis the user,sname.
WordGuessSpecification
WordGuess is played between the computer and a single player. The
secretword is BRAIN. At the start of the game, six dashesare displayed
(------), onefor eachletter of the word. The player is repeatedlyprompted
for a letter guess.When a letter matching one in the word is guessed,the
letter replacesthe corresponding dash. Letters may be entered as upper-
caseor lowercase.Howevet only uppercaseletters should be displayed. If
the player entersan exclamationpoint (!), the player is prompted to guess
the word. At that point the player either wins (a correct guess)or loses
(an incorrect guess).Alternatively, the player can continue to guessletters
until the entire word is revealed.The games ends by showing the player
the total number of guesses.
WorAGuess
aame.
The WordGuessalgorithm:
1. Display a row of dashesto representthe word.
2. Prompt the user for a letter guess.
3. If the letter guessedis part of the word, then display that letter in
place of the corresponding dash.
4. Repeatsteps2 and 3 until all the lettershave been guessedor an
exclamation point has been entered by the user.
5. If an exclamationpoint hasbeenentered,prompt the user to guess
the entire word.
6. If the player correctly guessesthe entire word or all the letters have
been guessed,then display a messageindicating that the player
has won, otherwise the messageshould indicate that the player
has lost.
7. Display the secretword and the number of guesses'
andstrings
chapter6 Loop structures
n
The WordGuessflowchart:
lncremenl
queescounT,er
Oel wordque6a
rrom ?Eye?
"Youlose"
me99aqe
DioplayeecreNwordand
numberof auessesNaken
do
rrndaFe drcssFs counLer
Promnt- rrser fnr: a letter
Convert to all uppercase
Determine if letter is in word
if letter
is in woril
Create new string that contains the guessed letter
while (al1 letters haven't been guessed and user hasn't chosen
to guess the entire worcl)
if ( ! has been entered)
get a word guess from player
convert woril to all uppercase
if (word guessed equals secret word 0R all- the letters have
been guessed)
display message that pJ-ayer has won
else
rii enl:rr th:t nl errcr hac Inqr
WordGuessImplementation
Basedon the codedesign,the WordGuessimplementationfollows:
* WordGuess.java
/* begin game */
System. out. println ( " W o r i l G u e s s g a m e .\ n " ) ;
for (int i = 0; i < SECRET_W0RD.1ength0; i++) {
wordSoFar += "-"; //word, as dashes
)
System.out.println(worclSoFar + "\n") ; //clisplay ilashes
if (SECRET_WORD.inclexOf(letcerGuess) >= 0) {
updateclWord = worclSoFar.substring(0, SECRET W0RD.indexOf(letterGuess));
updateclWord += lettercuess;
updateilltloril += worilSoFar.substring(SECRET WORD.inclexOf(letterGuess)+1,
worclSoFar. length ( ) ) ;
worclSoFar = upilateclWord;
]
Chapter6 LoopStructures
and Strings
E
A run of WordGuesslooks similar to:
U o r d G u e s sg a n e .
E n t e r a l e t t e r ( ! t o g u e s se n t i r e r . r o r d )
B - 4 .-
Modify the WordGuessChapter6 CaseStudy to display a scoreat the end of eachgame.The player should
start with 100points and have 10points taken off for eachguess.The scoreshould be updated and displayed
as the game is played. Display a player losesmessageif the scoregets down to 0.
Counters are used for keeping track of loop iterations and are used
in applications that keep track of the number of guesses or the number
of values entered. An accumulator is increased by varying amounts.
Accumulators are often used to sum values. Both counters and accumula-
tors should be initialized when they are declared.
A flag, also called a sentinel, is used to signify that a loop should stop
iterating. Flags are usually a constant that is declared in the application,
but may also be determined by prompting the user for a value.
The for statement is another loop structure. This loop structure executes
a set of statements a fixed number of times. A loop control variable is used
to determine loop iterations and can be declared in the f"' statement itself.
When a variable is declared in a statement, its scope is limited to the open-
ing and closing curly braces of that statement. The increment operator (++)
and decrement operator (--) are used to increase or decrease the value of
a for loop control variable.
Exercise 2 PrimeFactors
The Fundamental Theorem of Arithmetic statesthat every positive integer is the product of a set of
prime numbers. This set is called the prime factors. For example,the prime factors for 140 are 2,2,5,
andT (2*2*5*7= 140).Createa PrimeFactorsapplicationthat prompts the user for a positive integer
and then displays that integer'sprime factors.Use the following pseudocodewhen implementing the
PrimeFactorscode:
fnitialize a counter to 2
while the counter is less than or equal to the number
if the counter ilivicles the nunber evenlv
ilisplay the counter
ilivicle the
number by the counter to get a new number
else increment counter bv 1
Exercise 3 Investment
Createan Investmentapplicationthat calculateshow many years it will take for a $2,500investment
to be worth at least$5,000if compoundedannually at7.5%
Exercise 4 CarRecall
Modify the CarRecall application created in Chapter 5 Exercise4 to allow the user to input as many
model numbers as needed. Use 0 as a sentinel to end user input. The application output should look
similar to:
Exercise 6 DigitsSum
Createa DigitsSum application that prompts the user for a non-negativeinteger and then displays the
sum of the digits. Application output should look similar to:
Exercise 7 CubesSum
a) Createa CubesSumapplication that prompts the user for a non-negative integer and
then displays the sum of the cubesof the digits. Application output should look similar
to:
b) Modify the application to determine what integers of two, three, and four digits are
equal to the sum of the cubesof their digits.
Exercise 8 g GuessingGame
The GuessingGameapplication createdin Chapter 5 Exercise8 would be more fun if userscould make
as many guesses'asnecessaryto guessthe secretnumber. Modify the CuessingGameapplicationas
follows:
In another program run, assuming the random number generatedis 20, the game
would play out as follows using the samedivide-and-conquer technique:
When this approachis taken, it has been proven that a player will not be required
to make more than Logrn guesses,in this caseLogr50,or at most 6 guesses.Try this
technique yourself. Explain in your own words why this works. Would this strategy
be possibleif hints were not given after eachguess?
Exercise 9 PowersTable
Createa Powerslable application that displays a table of of powers similar to:
e Chapter6 Loopstructures
andstrings
Exercise 10 GCD
Create a GCD application that prompts the user for two non-negative integers and then displays the
greatestcommon divisor (GCD) of the two numbers. The GCD is the largest integer that divides into
both numbers evenly. An algorithm for finding the GCD is called Euclid's Algorithm. Use the follow-
ing pseudocodewhen implementing the GCD code:
while (num2 > 0) {
temp=num1%num2;
numl = num2;
num2 = temn:
]
Application output should look similar to:
Enter a nurnher: 32
Enter a second nunher: 4E
The GCD is I
Exercise 11 ElapsedTimeCalculator
What comes13hours after 4 otlock? Createan ElaspsedTimeCalculator applicationthat prompts the
user for a starting hour, whether it is am or pm, and the number of elapsedhours. The application then
displaysthe time after that many hours havepassed.Application output should look similar to:
Exercise t2 Necklace
An interestingproblem in number theory is sometimescalled the "necklaceproblem." This problem
begins with two single-digitnumbers.The next number is obtainedby adding the first two numbers
togetherand saving only the onesdigit. This processis repeateduntil the "necklace"closesby return-
ing to the original two numbers.For example,if the starting two numbersare 1 and 8, twelve stepsare
requiredto closethe necklace:1.89 7 63 9 21 3 47 1 8
Createa Necklaceapplicationihat prompts the user for two single-digitintegersand then displaysthe
sequenceand the number of stepstaken.The applicationoutput should look similar to:
Exercise L4 DiceRolls
Create a DiceRolls application that displays five rolls of two dice where each die is numbered from L
to 6. The applicationshould also show the total of eachroll:
DicelDice2 Total
61?
6418
336
358
314
Exercise 15 Chaos
"Chaos theory" is a subfield of mathematicswhich relies heavily on the computer.A simple chaos
experimentis:
Start with any real number x between 0 and 1. Generatea new number using the
"logistic equation:"
x=2*x(1 -x)
Createa RandomWalk application that determineshow many stepsthe person will walk before taking
a step off the bridge, Have the application average50 trials, and display the averageand the greatest
number of steps.(Hint: Generatea random number between 0 and 1, with 0 meaning to go forward
and 1 meaning to go backward.)
Exercise 17 Password
Createa Passwordapplicationthat storesa secretpasswordof your choice.The Passwordapplication
shouldprompt the userfor the passwordand then display "Welcome"if the correctpasswordis typed.
If after three tries the correctpasswordhas not been entered,the message'Accessdenied." should be
displayed.Application output should look similar to:
Exercise 18 Monogram
Createa Monogram application that prompts the user for his or her first name, middle name, and last
name and then displays a monogram with the first and middle initials in lowercaseand the last initial
in uppercase.Application output should look similar to:
Exercise 19 RemoveString
Create a RemoveStringapplication that prompts the user for a sentenceand a string. The application
should then remove every occurrence of the string from the sentence.The application should look
similar to:
Exercise 2I GroupAssignment
Createa GroupAssignment application that prompts the user for his or her name and then displays a
group assignment.The group assignment depends on the first letter of the student's last name. Last
namesbeginning with A through I are assignedto Group 1, J through S are assignedto Group 2, T
through Z are assignedto Group 3. Application output should look similar to:
E chapter6 Loopstructures
andstrings