Control Statements: Part 2: Objectives
Control Statements: Part 2: Objectives
Control
Not everything that can be
Statements: Part 2
counted counts, and not
every thing that counts can
be counted.
—Albert Einstein
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 117
Assignment Checklist
Name: Date:
Section:
Prelab Activities
Matching YES NO
Fill in the Blank 13, 14, 15, 16, 17, 18, 19, 20, 21
Short Answer 22, 23, 24, 25, 26
Programming Output 27, 28, 29, 30, 31, 32, 33, 34, 35,
36
Correct the Code 37, 38, 39, 40
Lab Exercises
Exercise 1 — Triangles YES NO
Follow-Up Question and Activity 1
Exercise 2 — Sales YES NO
Follow-Up Questions and Activities 1, 2
Exercise 3 — Pythagorean Triples YES NO
Follow-Up Questions and Activities 1, 2, 3
Debugging YES NO
Labs Provided by Instructor
1.
2.
3.
Postlab Activities
Coding Exercises 1, 2, 3, 4, 5, 6, 7, 8
Programming Challenges 1, 2
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 119
Prelab Activities
Matching
Name: Date:
Section:
After reading Chapter 5 of Java How to Program: Seventh Edition, answer the given questions. These questions
are intended to test and reinforce your understanding of key Java concepts. You may answer these questions ei-
ther before or during the lab.
For each term in the left column, write the letter for the description that best matches the term from the right
column.
Term Description
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 121
Name: Date:
Section:
13. The %b format specifier causes the value of a boolean expression to be output as the word or the
word based on the expression’s value.
14. Typically, statements are used for counter-controlled repetition and statements are
used for sentinel-controlled repetition.
15. In most programs, it is necessary to include a(n) statement after the statements for each case in a
switch statement.
16. The of a variable defines where it can be referenced in a program by using just the variable’s
name.
18. Placing a semicolon after the header of a for statement is normally a(n) error.
20. Infinite loops occur when the loop-continuation condition in a repetition statement never becomes
.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 123
Short Answer
Short Answer
Name: Date:
Section:
Answer the following questions in the space provided. Your answers should be concise; aim for two or three sen-
tences.
23. Why should programs control counting loops with integers and not with floating-point numbers?
24. Explain why placing a semicolon after the header of a for statement is a logic error and not a compilation
error.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
124 Control Statements: Part 2 Chapter5
Short Answer
25. Differentiate between the while and the do…while repetition statements.
26. Explain why an infinite loop can occur and how one can be prevented.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 125
Programming Output
Programming Output
Name: Date:
Section:
For each of the given program segments, read the code and write the output in the space provided below each
program. [Note: Do not execute these programs on a computer.]
For the following questions, assume that the code segments are contained within the main method of a Java ap-
plication.
1 int startingValue;
2 int terminatingValue;
3 int stepValue;
4
5 for ( int i = startingValue; i < terminatingValue; i += stepValue )
6 System.out.printf( "%d ", i );
27. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = 0;
2 terminatingValue = 5;
3 stepValue = 1;
Your answer:
28. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = -3;
2 terminatingValue = 2;
3 stepValue = 1;
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
126 Control Statements: Part 2 Chapter5
Programming Output
29. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = 6;
2 terminatingValue = 5;
3 stepValue = 1;
Your answer:
30. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = 0;
2 terminatingValue = 5;
3 stepValue = 3;
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 127
Programming Output
1 int startingValue;
2 int terminatingValue;
3 int stepValue;
4
5 for ( int i = startingValue; i <= terminatingValue; i += stepValue )
6 {
7 switch( i )
8 {
9 case 0:
10 System.out.print( "Hello there, " );
11 break;
12 case 1:
13 System.out.println( "What’s up? " );
14 break;
15 case 2:
16 System.out.println( "How are you doing? " );
17 break;
18 case 3:
19 System.out.println( "Terrific. " );
20 break;
21 case 4:
22 System.out.println( "Beautiful day isn't it? " );
23 break;
24 case 5:
25 System.out.println( "Yes it is. " );
26 break;
27 default:
28 System.out.println( "See you later. " );
29 } // end switch
30 } // end for
31. What will be the output if the following code is placed at line 4 of the preceding class definition?
1 startingValue = 0;
2 terminatingValue = 6;
3 stepValue = 2;
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
128 Control Statements: Part 2 Chapter5
Programming Output
32. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = 0;
2 terminatingValue = 6;
3 stepValue = 3;
Your answer:
33. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = -3;
2 terminatingValue = 2;
3 stepValue = 1;
Your answer:
34. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = -5;
2 terminatingValue = 1;
3 stepValue = 2;
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 129
Programming Output
35. What will be the output if the following code is placed at line 4 of the preceding code?
1 startingValue = 10;
2 terminatingValue = 5;
3 stepValue = 1;
Your answer:
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 131
Name: Date:
Section:
Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a compilation error, circle the error in the program and write the corrected code in the space
provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more
than one error in each program segment.]
37. The following for loop should calculate the product of the integers in the range 1–5.
Your answer:
38. The following for loop should print the sum of consecutive odd and even integers in the range 1–10. The
expected output is shown below the code.
1 + 2 = 3
3 + 4 = 7
5 + 6 = 11
7 + 8 = 15
9 + 10 = 19
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
132 Control Statements: Part 2 Chapter5
39. The following for loop should loop 10 times and compute the product of i times 2 plus 1 in each iteration.
For example, if the loop counter is 4, the program should print 4 * 2 + 1 = 9.
Your answer:
40. The following switch statement should print either "x is 5", "x is 10" or "x is neither 5 nor 10".
1 switch ( x )
2 {
3 case 5:
4 System.out.println( "x is 5" );
5 break;
6 case 10:
7 System.out.println( "x is 10" );
8 break;
9 default:
10 System.out.println( "x is neither 5 nor 10" );
11 break;
12 } // end switch
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 133
Lab Exercises
Lab Exercise 1 — Triangles
Name: Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Problem Description
3. Sample Output
4. Program Template (Fig. L 5.1 and Fig. L 5.2)
5. Problem-Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the output, then study the template code. Using the
problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program.
Compare your output with the sample output provided. Then answer the follow-up question. The source code
for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi-
tion. In this lab, you will practice:
• Nested for loops.
• Using counter-controlled repetition.
The follow-up question and activity also will give you practice in:
• Using techniques from one program to perform a similar task in another program.
Problem Description
Write an application that displays the following patterns separately, one below the other. Use for loops to gen-
erate the patterns. All asterisks (*) should be printed by a single statement of the form
System.out.print( "*" );
which causes the asterisks to print side by side. A statement of the form
System.out.println();
can be used to display a space for the last two patterns. There should be no other output statements in the pro-
gram.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
134 Control Statements: Part 2 Chapter5
Sample Output
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 135
Template
1 // Lab 1: Triangles.java
2 // Program prints four triangles, one below the other
3 public class Triangles
4 {
5 // draw four triangles
6 public void drawTriangles()
7 {
8 int row; // the row position
9 int column; // the column position
10 int space; // number of spaces to print
11
12 // first triangle
13 /* Write code to display the first triangle. Use nested for loops. The
14 outer loop should control which row of asterisks is being displayed.
15 The inner loop should display one asterisk at a time. */
16
17 // second triangle
18 /* Write code to display the second triangle using techniques similar to
19 the first triangle */
20
21 // third triangle
22 /* Write code to display the third triangle. The outer for loop should
23 contain two separate inner for loops--one to display spaces and one to
24 display asterisks. */
25
26 // fourth triangle
27 /* Write code to display the fourth triangle using techniques similar to
28 the third triangle. */
29 } // end method drawTriangles
30 } // end class Triangles
1 // Lab 1: TrianglesTest.java
2 // Test application for class Triangles
3 public class TrianglesTest
4 {
5 public static void main( String args[] )
6 {
7 Triangles application = new Triangles();
8 application.drawTriangles();
9 } // end main
10 } // end class TrianglesTest
Problem-Solving Tips
1. For the first triangle use a nested for statement in which the outer loop counts rows and the inner loop
counts columns. The inner loop for the first triangle should count from 1 to the current row number.
2. For the second triangle use a nested for statement in which the outer loop counts backward from 10 to
1. The inner loop should be identical to the one used for the first triangle.
3. The last two patterns require that each row begin with an appropriate number of blank spaces.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
136 Control Statements: Part 2 Chapter5
4. For the third and fourth triangles use two separate inner loops—one for displaying spaces and one for
displaying asterisks.
5. If you have any questions as you proceed, ask your lab instructor for assistance.
*********
*******
*****
***
*
*
***
*****
*******
*********
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 137
Name: Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Problem Description
3. Sample Output
4. Program Template (Fig. L 5.3 and Fig. L 5.4)
5. Problem-Solving Tips
6. Follow-Up Questions and Activities
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the output, then study the template code. Using the
problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program.
Compare your output with the sample output provided. Then answer the follow-up questions. The source code
for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi-
tion. In this lab, you will practice:
• Using switch statements.
The follow-up questions and activities also will give you practice:
• Validating the input from the user.
• Extending an existing program.
Problem Description
A mail-order house sells five products whose retail prices are as follows: Product 1, $2.98; product 2, $4.50; prod-
uct 3, $9.98; product 4, $4.49 and product 5, $6.87. Write an application that reads a series of pairs of numbers
as follows:
a) product number
b) quantity sold
Your program should use a switch statement to determine the retail price for each product. It should calculate
and display the total retail value of all products sold. Use a sentinel-controlled loop to determine when the pro-
gram should stop looping and display the final results.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
138 Control Statements: Part 2 Chapter5
Sample Output
Product 1: $14.90
Product 2: $0.00
Product 3: $0.00
Product 4: $0.00
Product 5: $68.70
Template
1 // Lab 2: Sales.java
2 // Program calculates sales, based on an input of product
3 // number and quantity sold
4 import java.util.Scanner;
5
6 public class Sales
7 {
8 // calculates sales for 5 products
9 public void calculateSales()
10 {
11 Scanner input = new Scanner( System.in );
12
13 double product1 = 0; // amount sold of first product
14 double product2 = 0; // amount sold of second product
15 double product3 = 0; // amount sold of third product
16 double product4 = 0; // amount sold of fourth product
17 double product5 = 0; // amount sold of fifth product
18
19 /* Ask the user to enter product number */
20
21 /* Create while statement that loops until sentinel is entered */
22
23 /* Determine whether user’s product number is in 1-5 */
24
25 /* If so, ask user to input the quantity sold */
26
27 /* Write a switch statement here that will compute the total
28 for that product */
29
30 /* If product number is not in 1-5, test if product number is not 0 */
31 /* Display error message for invalid product number */
32
33 /* Ask the user to enter another product number */
34
35 /* end while loop */
36
37 // print summary
38 System.out.println();
39 System.out.printf( "Product 1: $%.2f\n", product1 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 139
40 /* write code here for the rest of the summary message it should contain
41 the totals for the rest of the products, each on it’s own line */
42 } // end method calculateSales
43 } // end class Sales
1 // Lab 2: SalesTest.java
2 // Test application for class Sales
3 public class SalesTest
4 {
5 public static void main( String args[] )
6 {
7 Sales application = new Sales();
8 application.calculateSales();
9 } // end main
10 } // end class SalesTest
Problem-Solving Tips
1. Before your while loop, request the first product number from the user.
2. Use a sentinel value to control the loop. This loop should terminate when the product number entered
is zero.
3. If the user provides a valid product number, inside the loop, request a quantity for that product. Then,
perform the appropriate calculation in the switch statement.
4. Your switch statement should consist of five cases, each setting the correct dollar value, depending on
the quantity that the user entered.
5. Inside the closing right brace (}) of the loop’s body, request the next product number from the user.
6. Be sure to follow the spacing and indentation conventions mentioned in the text. Before and after each
control statement, place a line of vertical space to make the code more readable.
7. If you have any questions as you proceed, ask your lab instructor for assistance.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 141
Name: Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Problem Description
3. Sample Output
4. Program Template (Fig. L 5.5)
5. Problem-Solving Tips
6. Follow-Up Questions and Activities
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the output, then study the template code. Using the
problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program.
Compare your output with the sample output provided. Then answer the follow-up questions. The source code
for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi-
tion. In this lab, you will practice:
• Nested for loops.
• Using counter-controlled repetition.
• Using “brute force” techniques to solve a problem.
The follow-up questions and activities will also give you practice:
• Using break statements.
• Using continue statements.
• Using counters to determine the number of iterations a loop performs.
Problem Description
A right triangle can have sides whose lengths are all integers. The set of three integer values for the lengths of the
sides of a right triangle is called a Pythagorean triple. The lengths of the three sides must satisfy the relationship
that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an application to
find all Pythagorean triples for side1, side2 and the hypotenuse, all no larger than 500. Use a triple-nested for
loop that tries all possibilities. This method is an example of “brute-force” computing. You will learn in more
advanced computer science courses that there are large numbers of interesting problems for which there is no
known algorithmic approach other than using sheer brute force.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
142 Control Statements: Part 2 Chapter5
Sample Output
s1: 3, s2: 4, h: 5
s1: 4, s2: 3, h: 5
s1: 5, s2: 12, h: 13
s1: 6, s2: 8, h: 10
s1: 7, s2: 24, h: 25
.
.
.
Template
1 // Lab 3: Triples.java
2 // Program calculates Pythagorean triples
3 public class Triples
4 {
5 public static void main( String args[] )
6 {
7 // declare the three sides of a triangle
8 int side1;
9 int side2;
10 int hypotenuse;
11
12 /* Write loop for side1 to try the values 1-500. */
13
14 /* Write loop for side2 to try the values 1-500. */
15
16 /* Write loop for hypotenuse to try the values 1-500 */
17
18 /* Write an if statement that determines whether the sum of the
19 two sides squared equals the hypotenuse squared. If this
20 condition is true display side1, side2 and hypotenuse. */
21 } // end main
22 } // end class Triples
Problem-Solving Tips
7. This program does not require any input from the user.
8. The formula for the Pythagorean Theorem is hypotenuse2 = side12 + side22.
9. Do not be concerned about trying values that do not make sense, such as a 1-500-1 triangle. Brute-force
computing techniques try all possible values.
10. Use an if statement to determine whether the sum of the two squared sides is equal to the hypotenuse
squared. If so, output side1, side2 and hypotenuse.
11. If you have any questions as you proceed, ask your lab instructor for assistance.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 143
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 145
Debugging
Debugging
Name: Date:
Section:
The program in this section does not run properly. Fix all the compilation errors, so that the program will com-
pile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic
errors that exist. The sample output demonstrates what the program’s output should be once the program’s code
is corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel.
Sample Output
Enter number: 20
Enter number: 6
Enter number: 15
Enter number: 28
Enter number: 5
********************
******
***************
****************************
*****
Broken Code
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
146 Control Statements: Part 2 Chapter5
Debugging
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 147
Debugging
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 149
Postlab Activities
Coding Exercises
Name: Date:
Section:
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.
For each of the following problems, write a program or a program segment that performs the specified action.
1. Write a for loop that prints all the odd integers from 1 to 100, inclusive.
3. Write a for loop that counts from 1 to 5. Use a switch statement to display a letter in the alphabet that
corresponds to the number (i.e., 1 is A, 2 is B, etc.).
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
150 Control Statements: Part 2 Chapter5
Coding Exercises
4. Write a while loop that sums the integers from 1 to 10, excluding 3 and 6. Print the sum.
5. Write a for loop that attempts to display the numbers from 1 to 10, but terminates when the control vari-
able reaches the value 6.
6. Write a for loop to display the numbers from 1 to 10, but skip the value 6 by using a continue statement.
7. Modify your solution in Coding Exercise 6 to use a while statement instead of a for statement.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 151
Coding Exercises
8. Modify your solution in Coding Exercise 7 to use a do…while statement instead of a while statement.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 153
Programming Challenges
Programming Challenges
Name: Date:
Section:
The Programming Challenges are more involved than the Coding Exercises and may require a significant amount
of time to complete. Write a Java program for each of the problems in this section. The answers to these problems
are available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Pseudocode, hints or sample
outputs are provided for each problem to aid you in your programming.
1. Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and
pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. Write an application
that evaluates the factorials of the integers from 1 to 5. Display the results in tabular format. What difficulty
might prevent you from calculating the factorial of 20?
Hints:
• Use nested for loops in this exercise.
• The inner for loop should compute the factorial.
• Your output should appear as follows:
X X!
1 1
2 2
3 6
4 24
5 120
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
154 Control Statements: Part 2 Chapter5
Programming Challenges
2. (“The Twelve Days of Christmas” Song) Write an application that uses repetition and switch statements to
print the song “The Twelve Days of Christmas.” One switch statement should be used to print the day (i.e.,
“First,” “Second,” etc.). A separate switch statement should be used to print the remainder of each verse.
Visit the Web site www.12days.com/library/carols/12daysofxmas.htm for the complete lyrics of the
song.
Hints:
• For this example you will need two switch statements.
• Both switch statements should appear inside a for loop that will iterate through the twelve days.
• You will have one string to which more text is added during every iteration of the loop. The string will
be displayed after the loop terminates.
• Your output should appear as follows:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 155
Programming Challenges
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.