Java Programming 7th Edition Joyce Farrell Solutions Manualdownload
Java Programming 7th Edition Joyce Farrell Solutions Manualdownload
https://testbankdeal.com/product/java-programming-7th-edition-
joyce-farrell-solutions-manual/
https://testbankdeal.com/product/java-programming-7th-edition-joyce-
farrell-test-bank/
https://testbankdeal.com/product/java-programming-9th-edition-joyce-
farrell-solutions-manual/
https://testbankdeal.com/product/java-programming-8th-edition-joyce-
farrell-solutions-manual/
https://testbankdeal.com/product/fundamentals-of-financial-
management-13th-edition-brigham-test-bank/
Microeconomics Brief Edition 2nd Edition McConnell Test
Bank
https://testbankdeal.com/product/microeconomics-brief-edition-2nd-
edition-mcconnell-test-bank/
https://testbankdeal.com/product/statistics-informed-decisions-using-
data-4th-edition-michael-sullivan-test-bank/
https://testbankdeal.com/product/entrepreneurship-9th-edition-hisrich-
test-bank/
https://testbankdeal.com/product/sociology-the-essentials-9th-edition-
andersen-test-bank/
https://testbankdeal.com/product/international-money-and-finance-8th-
edition-melvin-test-bank/
Statistical Reasoning for Everyday Life 4th Edition
Bennett Test Bank
https://testbankdeal.com/product/statistical-reasoning-for-everyday-
life-4th-edition-bennett-test-bank/
Java Programming, Seventh Edition 6-1
Chapter 6
Looping
At a Glance
• Objectives
• Teaching Tips
• Quick Quizzes
• Additional Projects
• Additional Resources
• Key Terms
Java Programming, Seventh Edition 6-2
Lecture Notes
Overview
Chapter 6 covers looping structures. Students will learn to create definite and indefinite
loops using the while statement. Next, they will learn to use Java’s accumulating and
incrementing operators. Students will use for loops to create a definite loop and
do…while loops for use when a posttest loop is required. Finally, students will learn
how to create nested loops and how to improve loop efficiency.
Objectives
• Learn about the loop structure
• Create while loops
• Use shortcut arithmetic operators
• Create for loops
• Create do…while loops
• Nest loops
• Improve loop performance
Teaching Tips
Learning About the Loop Structure
1. Define a loop as a structure that allows repeated execution of a block of statements. The
loop body contains the block of statements.
2. Explain the purpose of a loop. Briefly introduce the three loop statements used in Java
that are listed on page 300.
3. Describe scenarios when looping is useful. If possible, equate the loop to a game or
real-life situation.
Teaching Repetition structures are the third and final type of program control structure
Tip along with sequence and decision.
1. Define a while loop. Discuss that the loop body will continue to execute as long as the
Boolean expression that controls the loop is true.
2. Define a definite loop and an indefinite loop. Explain when each is useful in a
program.
1. Note that a while loop can be used to create a definite loop—one that repeats a
predetermined number of times. A definite loop is controlled by a loop control
variable.
2. Review the flowchart and program statements in Figure 6-2 and Figure 6-4.
Teaching Note that the flowchart symbol for a decision—a diamond—is also used in a
Tip loop flowchart.
4. Explain the concept of an infinite loop, as shown in Figure 6-3. Note that it is easy to
make a mistake when programming a loop that results in an infinite loop.
Pitfall: Failing to Alter the Loop Control Variable Within the Loop Body
1. Discuss the importance of altering the loop control variable within the body of a loop.
2. Using the code in Figure 6-5, demonstrate the pitfall of forgetting to insert curly braces
around the loop body.
Teaching Remind students that they should attempt to terminate a program that they
Tip believe contains an infinite loop.
1. Using Figure 6-6, point out that a loop can have an empty body. Suggest to your
students that this should be avoided.
Java Programming, Seventh Edition 6-4
1. Definite loops are sometimes called counter-controlled loops. The loop control
variable must be changed to avoid an infinite loop.
2. Introduce the terms incrementing and decrementing. Figure 6-7 shows a loop
statement in which the loop control variable is decremented each time the loop
executes.
2. Note that indefinite loops are also commonly used to validate data. An example is seen
in Figure 6-10.
Validating Data
1. Define the term validating data. Provide a really good example of why validating data
is important.
2. Examine the shaded loop in Figure 6-10. Be sure to discuss with your class how this
loop functions. Point out that the loop continues to execute while the data is invalid.
The test in validating loops should check for invalid data, not valid data.
Teaching Validating data should be a very important topic in your lectures. Students
Tip should get into the habit of validating every input.
You Do It
1. Students should follow the steps in the book on pages 310–311 to create a Java
application that uses a loop to validate data entries.
Quick Quiz 1
1. True or False: Within a looping structure, a floating-point expression is evaluated.
Answer: False
2. A(n) ____ loop is one in which the loop-controlling Boolean expression is the first
statement in the loop.
Answer: while
3. To write a definite loop, you initialize a(n) ____, a variable whose value determines
whether loop execution continues.
Answer: loop control variable
4. A loop controlled by the user is a type of ____ loop because you don’t know how many
times it will eventually loop.
Answer: indefinite
Teaching Ask students to write several equivalent arithmetic statements using the normal
Tip and accumulating operators.
3. Introduce the prefix and postfix increment operators and decrement operators.
Review the program in Figure 6-13 to discuss the use of these operators.
4. Write code during your lectures that uses several of the operators presented in this
section.
Java Programming, Seventh Edition 6-6
You Do It
1. Students should follow the steps in the book on pages 315–317 to create a Java
application that uses the prefix and postfix increment operators.
Teaching
Stress the difference between the prefix and postfix operators.
Tip
1. Define a for loop. Emphasize that the for loop is a definite loop. Discuss when the
for loop is appropriate in code. Contrast the for loop with the counter-controlled
definite while loop.
2. Using Figure 6-18, describe the program statements used in a for loop. The three
sections of a for loop are described on page 317. Discuss the different ways these
three sections may be used (listing on pages 318–319).
3. Point out that a for loop with an empty body is not infinite, and can be used to create a
brief pause in your program.
Teaching Remind students that a variable declared within a for loop is only accessible
Tip within the loop and goes out of scope when the loop exits.
You Do It
1. Students should follow the steps in the book on pages 320–321 to create a Java
application that uses a definite loop.
1. Explain that in both of the loop structures introduced in the chapter, while and for,
the body of the loop may not execute because the loop condition is checked before
entering the loop. This is known as a pretest loop.
Java Programming, Seventh Edition 6-7
2. In contrast, the body of a do…while loop will always execute at least once before the
loop condition is checked. This type of loop is called a posttest loop.
Teaching Provide examples of a situation for which it is desirable to use a pretest loop and
Tip one for which it is desirable to use a posttest loop.
3. Review the flowchart in Figure 6-20 and the program code in Figure 6-21.
4. Note that even though it is not required, it is a good idea to always enclose a single loop
statement within a block.
5. Revisit data validation. Point out that the code in Figure 6-10 asks for input both before
the loop and within the loop. The first input is called a priming input.
6. Recode the shaded portion of Figure 6-10 using a do…while loop. The use of the
do…while loop removes the need for the priming input. Code several other data
validation loops during your lecture.
Quick Quiz 2
1. The statement count ____1; is identical in meaning to count = count + 1.
Answer: +=
2. The prefix and postfix increment operators are ____ operators because you use them
with one value.
Answer: unary
3. The three elements within the for loop are used to ____, ____, and ____ the loop
control variable.
Answer: initialize, test, update
4. A while loop is a(n) ____ loop—one in which the loop control variable is tested
before the loop body executes.
Answer: pretest
5. The do…while loop is a(n) ____ loop—one in which the loop control variable is
tested after the loop body executes.
Answer: posttest
Java Programming, Seventh Edition 6-8
2. Make sure that students understand the terms inner loop and outer loop. Also, stress
that any type of loop can be nested within any other type (i.e., a for loop inside a
while loop).
4. Use the code on page 327 to discuss the importance of placing the inner and outer loops
correctly.
6. Code a nested loop with your class. A classic example is generating a multiplication
table.
You Do It
1. Students should follow the steps in the book on pages 328–329 to create a Java
application that uses nested loops to print a list of positive divisors.
1. Remind students that when a logical expression such as AND or OR is used, the
expression is only evaluated as far as necessary to determine the true or false
Java Programming, Seventh Edition 6-9
outcome. It is important to place the condition most likely to terminate the loop first,
especially with an inner loop. An example is shown on page 330.
Comparing to Zero
2. The example in Figure 6-27 creates and times two sets of nested do-nothing loops. The
second set of loops will execute faster than the first set of loops.
3. If time permits, execute the code in Figure 6-27 during your lecture.
1. Using prefix incrementing is slightly faster than using postfix incrementing. The code
shown in Figure 6-29 times two do-nothing loops that loop 1 billion times. The first
loop uses postfix loops; the second uses prefix loops.
2. Figure 6-30 proves that over the 1 billion loops, the prefix loop executes about one-
tenth of a second faster.
Figure 6-30 will result in different times depending on your system. The numbers
will likely not impress your students. To make the numbers relevant, calculate
Teaching
the time saved if this code is executed 1,000 times in a day. This saves 100
Tip
seconds, or nearly 3 minutes of processing time per day, or over 1,000 minutes
per year.
You Do It
1. Students should follow the steps in the book on pages 335–336 to create a Java
application that compares execution times for different loop techniques.
Don’t Do It
1. Review this section, discussing each point with the class.
Java Programming, Seventh Edition 6-10
Quick Quiz 3
1. When loops are ____, each pair contains an inner loop and an outer loop.
Answer: nested
2. True or False: When you use a loop within a loop, you should always think of the inner
loop as the all-encompassing loop.
Answer: False
3. True or False: Whether you decide to use a while, for, or do…while loop in an
application, you can improve loop performance by making sure the loop does not
include unnecessary operations or statements.
Answer: True
2. Why do you think the Java language provides three different types of loops if all loops
can be written using the while statement?
3. Modern processors run at over 3 GHz and have several cores. Given the speed of
modern computers, why is it still important to discuss performance issues?
Additional Projects
1. Create a Java program that uses nested loops to print out the following:
*
**
***
****
*****
2. A new variation on the for loop called the for each loop was introduced in Java 5.
Using the Internet, find a description of this loop and explain how it is different from a
standard for loop.
Additional Resources
1. The while and do-while Statements:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Key Terms
Accumulating: the process of repeatedly increasing a value by some amount to produce
a total.
Add and assign operator ( += ): alters the value of the operand on the left by adding
the operand on the right to it.
Counter-controlled loop: a definite loop.
Counting: the process of continually incrementing a variable to keep track of the
number of occurrences of some event.
Decrementing: reducing the value of a variable by 1.
Definite loop: a loop that executes a specific number of times; also called a counted
loop.
Divide and assign operator ( /= ): alters the value of the operand on the left by
dividing the operand on the right into it.
do…while loop: executes a loop body at least one time; it checks the loop control
variable at the bottom of the loop after one repetition has occurred.
Do-nothing loop: one that performs no actions other than looping.
Empty body: a block with no statements in it.
Event-controlled loop: an indefinite loop.
for loop: a special loop that can be used when a definite number of loop iterations is
required.
Incrementing: adding 1 to the value of a variable.
Indefinite loop: one in which the final number of loops is unknown.
Infinite loop: a loop that never ends.
Inner loop: contained entirely within another loop.
Iteration: one loop execution.
Loop: a structure that allows repeated execution of a block of statements.
Loop body: the block of statements that executes when the Boolean expression that
controls the loop is true.
Java Programming, Seventh Edition 6-12
Loop control variable: a variable whose value determines whether loop execution
continues.
Loop fusion: the technique of combining two loops into one.
Multiply and assign operator ( *= ): alters the value of the operand on the left by
multiplying the operand on the right by it.
Outer loop: contains another loop.
Postfix ++: evaluates a variable and then adds 1 to it.
Postfix increment operator: another name for postfix ++.
Posttest loop: one in which the loop control variable is tested after the loop body
executes.
Prefix ++: adds 1 to a variable and then evaluates it.
Prefix and postfix decrement operators: subtract 1 from a variable. For example, if b
= 4; and c = b--;, 4 is assigned to c, and then after the assignment, b is decreased
and takes the value 3. If b = 4; and c = --b;, b is decreased to 3, and 3 is
assigned to c.
Prefix increment operator: another name for prefix ++.
Pretest loop: one in which the loop control variable is tested before the loop body
executes.
Priming input: another name for a priming read.
Priming read: the first input statement prior to a loop that will execute subsequent
input statements for the same variable.
Remainder and assign operator ( %= ): alters the value of the operand on the left by
assigning the remainder when the left operand is divided by the right operand.
Subtract and assign operator ( –= ): alters the value of the operand on the left by
subtracting the operand on the right from it.
Validating data: the process of ensuring that a value falls within a specified range.
while loop: executes a body of statements continually as long as the Boolean
expression that controls entry into the loop continues to be true.
Other documents randomly have
different content
Un vendredi treize—Georges en devint superstitieux par la suite—
sous une pluie tiède de mai, la voiture l’attendait à six heures et
demie, rue du Havre, à la porte du lycée. Dans la calèche, au lieu de
Mme Aymeris, était assise la tante Lili. Elle désigna à Georges une
petite malle qu’il fallut enjamber pour s’asseoir sur la banquette.
—A qui cela, tante?
—Nous passerons par la gare de l’Est avant de rentrer, mon chou.
Octave a porté le bagage de la Jessie au chemin de fer et ce colis a
été oublié. Il faut que nous le fassions enregistrer pour Cologne.
Georges presse sa tante Lili de questions; il n’obtient que cette
réponse:
—Nul à la maison ne t’en dira rien, c’est plus convenable, mais la
maison est nettoyée! Les intrus ont été flanqués dehors et ce n’est
pas trop tôt! Ta chère compagne est partie. Elle sera demain matin
dans un couvent sur les bords du Rhin. Ne demande pas
d’explications! Tout est pour le mieux. Papa et maman ont été bien
inconséquents. Vois-tu, mon petit chéri, on a assez de ses propres
parents. A un certain point, bonté et bêtise ne font qu’un. Ta mère
est trop généreuse. Ton père a ses occupations; sans cela, c’est lui
qui aurait depuis beau temps fait la lessive de ce linge sale...
Georges, dégoûté par ce ton vulgaire, fait arrêter la voiture, crie
à sa tante:—Menteuse!—et rentre à pied.
Le récit de Mlle Aymeris n’était point exact... Ellen Gonnard était
encore dans son pavillon. Le lendemain matin, un pot de faïence à la
main, elle se rendait à la loge de la concierge où l’on déposait le lait
pour son ménage. Gonnard ne l’accompagnait pas jusqu’à la grille,
comme d’ordinaire, quand il s’en allait au manège, la taille pincée,
les jambes arquées et faisant sonner ses éperons; aujourd’hui, Ellen
était seule, les yeux rougis par les larmes. L’atmosphère de la
maison était plus lourde encore que de coutume. Avant de se
remettre en route pour Fontanes, muet, Georges prit son thé dans la
chambre de sa mère. Mme Aymeris, enfin, jugea nécessaire de
rompre le silence:
—Tu sais, Jessie est dans un couvent... Il fallait compléter son
éducation; une occasion s’est offerte, elle est partie hier. Elle sera
heureuse là-bas. La pauvre enfant m’a donné un témoignage de
confiance et d’affection que j’eusse à peine attendu de sa part. Elle
m’a chargée de te demander pardon.
Georges détourna la tête. Mme Aymeris reprit:
—Sache seulement que M. Gonnard est un misérable; il était
cruel pour sa femme et sa belle-sœur. Si je te disais tout, tu ne
comprendrais pas... Ton père a séparé le couple, et délivré Jessie qui
était sous la domination de son coquin de beau-frère. Nous ne
verrons plus ce bellâtre. J’espère qu’Ellen tiendra ferme; je vais
l’expédier en Angleterre, je ne sais encore où... Mon chéri, ne me
pose pas de questions! Peut-être plus tard... Mais pourquoi pleures-
tu? Tu aimais donc Jessie comme une sœur? Elle ne le méritait
guère, dis-toi bien cela!...
Georges ne se contient plus; il est secoué de hoquets, puis,
retrouvant l’usage de la parole, se détache des bras de sa mère:
—Maman, ne m’interroge pas non plus! Je ne pourrai plus vivre
sans la compagne que vous m’aviez donnée; c’est vous qui l’aviez
choisie, et j’avais cru que c’était pour toujours! Laisse-moi, ne me
plains pas. Allons, adieu, Maman! Je retourne à mon travail, n’en
parlons plus...
Deux heures plus tard, des agents de police sautaient hors d’un
fiacre, sonnaient à la porte. Ils accompagnaient Georges qu’ils
venaient de relever sur la ligne du tramway. La jambe gauche était
brisée, à la hauteur du genou; le visage avait porté, le sang coulait.
Les portes claquèrent, maîtres et serviteurs furent, en un instant,
autour de Georges, qui eut encore la force de gémir:
—Pas de mal! je ne suis pas mort! Je ne sais pas encore sauter
de la plate-forme de ces nouveaux omnibus à rails! J’ai été traîné,
cinquante mètres!
Le chirurgien lava le genou, inspecta la plaie, prit une mine
sérieuse, ne se prononça pas. L’accident était inexplicable.
Désespoir? Tentative de... Pourquoi?
Des mois, Georges resta étendu; il ne devait plus jamais marcher
sans une légère claudication. Pendant des jours et des nuits, gardé
par la vieille nourrice, dégoûté de lire, toujours songeant à Jessie, il
tâcha de reconstruire le drame qui avait précédé la fuite de sa
compagne et de Gonnard. Avec Nou-Miette, il s’enhardissait parfois,
comptant sur l’indiscrétion de cette bavarde.
Elle se fit beaucoup prier.
—Enfin, Miette, dis-moi donc ce qui s’est passé! Il faut que je le
sache! Je ne suis plus un enfant; raconte, je te jure que personne
d’ici n’en saura rien! Je devrais bien être mort, au lieu de Jacques!...
—Laisse-moi donc tranquille! mon petit doigt me disait que ces
gens-là ne valaient pas la corde pour les pendre; pas la pauvre
idiote, mais ces Gonnard!... Il y a des choses qu’une femme de mon
âge aurait honte de te raconter, mon pauvre chéri! Ah! c’est un
animal, une bête brute, ce Gonnard. Ellen l’aimait trop; elle se serait
«endêvée» pour lui. Il voulait la quitter, elle a voulu le retenir; avec
ce cochon-là, elles avaient fait un marché... Mais non, je ne veux
pas!... Enfin Jessie est venue implorer ta maman de la faire partir au
loin.
Et Georges, tout d’un coup, se rappela un rêve atroce, de
plusieurs mois auparavant. Il avait vu Jessie exsangue, gémissante,
fouettée par sa sœur dans une chambre d’hôtel, sur un lit aux draps
défaits, maintenue par Gonnard qui avait, comme Viterbo, des
pantalons à patte d’éléphant et une raie au milieu du front.
—Etait-ce un cauchemar, ou la réalité? Lui-même n’était-il pas, en
ce moment, la proie d’une hallucination?
La vie des hommes est si drôle et si triste! Jacques et Marie
devaient être bien mieux, là-bas, au Paradis...
2.
Lucia
LUCIA
testbankdeal.com