0% found this document useful (0 votes)
74 views

Control Statements: Part 2: Objectives

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Control Statements: Part 2: Objectives

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

5

Control
Not everything that can be
Statements: Part 2
counted counts, and not
every thing that counts can
be counted.
—Albert Einstein

Who can control his fate?


—William Shakespeare
OBJECTIVES
The used key is always bright. In this chapter you will learn:
—Benjamin Franklin
■ The essentials of counter-controlled repetition.
Intelligence … is the faculty ■ To use the for and do…while repetition statements
of making artificial objects, to execute statements in a program repeatedly.
especially tools to make tools.
—Henri Bergson ■ To understand multiple selection using the switch
selection statement.
Every advantage in the past
is judged in the light of the ■ To use the break and continue program control
final issue. statements to alter the flow of control.
—Demosthenes
■ To use the logical operators to form complex
conditional expressions in control statements.

© 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:

Exercises Assigned: Circle assignments Date Due

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

1. && a) Handles a series of decisions, in which a particular vari-


2. || able or expression is tested for values it can assume and
different actions are taken.
3. !
4. switch b) Skips any remaining statements in the body of a repeti-
tion statement and proceeds with the next iteration of
5. continue the loop.
6. break c) Boolean logical AND
7. for repetition statement d) Handles all of the details of counter-controlled repeti-
8. do…while repetition statement tion.
9. | e) Conditional AND.
10. off-by-one error f) Causes immediate exit from a repetition statement.
11. & g) Can be caused by the use of an incorrect relational oper-
12. constant ator or using an incorrect final value of a loop counter in
the condition of a repetition statement.
h) Conditional OR.
i) Boolean logical inclusive OR.
j) Logical negation.
k) A variable which contains a value which does not change
for the entire program.
l) Repetition statement that tests the loop-continuation
condition at the end of the loop, so that the body of the
loop will execute at least once.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 121

Prelab Activities Name:

Fill in the Blank

Fill in the Blank

Name: Date:

Section:

Fill in the blanks for each of the following statements:

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.

17. operators may be used to form complex conditions by combining conditions.

18. Placing a semicolon after the header of a for statement is normally a(n) error.

19. Programs should control counting loops with values.

20. Infinite loops occur when the loop-continuation condition in a repetition statement never becomes
.

21. The expression in parentheses following keyword switch is called the .

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 123

Prelab Activities Name:

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.

22. What is required to perform counter-controlled repetition?

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

Prelab Activities Name:

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

Prelab Activities Name:

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.

For questions 27–30, use the following code segment:

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

Prelab Activities Name:

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

Prelab Activities Name:

Programming Output

For questions 31–35, use the following class definition:

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

Prelab Activities Name:

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

Prelab Activities Name:

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:

36. What is output by the following code segment?

1 for ( int i = 0; i <= 11; i++ )


2 {
3 if ( i % 2 == 0 )
4 continue;
5
6 if ( i == 11 )
7 break;
8
9 System.out.printf( "%d ", i );
10 } // end for

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 131

Prelab Activities Name:

Correct the Code

Correct the Code

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.

1 for ( int i = 1; i <= 5; i++ )


2 {
3 int product = 1;
4 product *= i;
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 for ( int i = 1, j = 1; i <= 10 && j <= 10; i++, j++)


2 System.out.printf( "%d + %d = %d\n", i, j, ( i + j ) );

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

Prelab Activities Name:

Correct the Code

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.

1 for ( int i = 1; i <= 10; i++ )


2 System.out.printf( "%d * 2 + 1 = %d", i, ( ++( i * 2 ) ) );
3

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 move to the next line. A statement of the form


System.out.print( " " );

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

Lab Exercises Name:

Lab Exercise 1 — Triangles

Sample Output

*
**
***
****
*****
******
*******
********
*********
**********

**********
*********
********
*******
******
*****
****
***
**
*

**********
*********
********
*******
******
*****
****
***
**
*

*
**
***
****
*****
******
*******
********
*********
**********

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 135

Lab Exercises Name:

Lab Exercise 1 — Triangles

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

Fig. L 5.1 | Triangles.java.

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

Fig. L 5.2 | TrianglesTest.java

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

Lab Exercises Name:

Lab Exercise 1 — Triangles

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.

Follow-Up Question and Activity


1. Using the techniques of the third and fourth triangles in Lab Exercise 1, display two triangles in the format
shown below.

*********
*******
*****
***
*
*
***
*****
*******
*********

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 137

Lab Exercises Name:

Lab Exercise 2 — Sales

Lab Exercise 2 — Sales

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

Lab Exercises Name:

Lab Exercise 2 — Sales

Sample Output

Enter product number (1-5) (0 to stop): 1


Enter quantity sold: 5
Enter product number (1-5) (0 to stop): 5
Enter quantity sold: 10
Enter product number (1-5) (0 to stop): 0

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 );

Fig. L 5.3 | Sales.java. (Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 139

Lab Exercises Name:

Lab Exercise 2 — Sales

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

Fig. L 5.3 | Sales.java. (Part 2 of 2.)

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

Fig. L 5.4 | SalesTest.java

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.

Follow-Up Questions and Activities


1. What happens when the user inputs a number that is other than 1 through 5 or 0? Why? What is the output
when the user enters a number like 7?
2. Modify the program so that there is a sixth product, priced at $20.00, that represents a package of all the
products. For each of the packages purchased, add $4.00 to the totals for all the other products. Do not keep
track of the packages separately.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 141

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Lab Exercise 3 — Pythagorean Triples

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

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

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

.
.
.

s1: 480, s2: 31, h: 481


s1: 480, s2: 88, h: 488
s1: 480, s2: 108, h: 492
s1: 480, s2: 140, h: 500
s1: 483, s2: 44, h: 485

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

Fig. L 5.5 | Triples.java.

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

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Follow-Up Questions and Activities


1. How many times did this program execute the innermost for loop? Add another counter to the program
that counts the number of times the inner loop iterates. Before exiting the program, display the counter
value.
2. Add a break statement to the program inside the innermost for loop. This break statement should execute
after the twentieth Pythagorean triple is found. Explain what happens to the program after the 20th triple
is found. Do all three for loops exit, or just the innermost one? What happens differently when the break
statement is placed inside the second loop? What happens differently when the break statement is placed
inside the outermost loop? [Hint: Use the loop counter you defined in the previous follow-up question to
count how many times the loops execute.]
3. Add a continue statement to the program that prevents a Pythagorean triple from being found when side1
is equal to 8. Using the loop counter again from Follow-Up Question 1, calculate how many times this new
program executed the innermost for loop. Explain how the continue statement affected the output.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 145

Lab Exercises Name:

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

1 // Debugging problem Chapter 5: Graphs.java


2 // Program prints 5 histograms with lengths determined by user.
3 import java.util.Scanner;
4
5 public class Graphs
6 {
7 // draws 5 histograms
8 public void drawHistograms()
9
10 Scanner input = new Scanner( System.in );
11
12 int number1 = 0; // first number
13 int number2 = 0; // second number
14 int number3 = 0; // third number
15 int number4 = 0; // fourth number
16 int number5 = 0; // fifth number
17
18 int inputNumber; // number entered by user
19 int value = 0; // number of stars to print
20 counter = 1; // counter for current number
21
22 while ( int counter <= 5 )
23 {
24 System.out.print( "Enter number: " );
25 inputNumber = input.nextInt();
26

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
146 Control Statements: Part 2 Chapter5

Lab Exercises Name:

Debugging

27 // define appropriate num if input is between 1-30


28 if ( inputNumber >= 1 && inputNumber <= 30 )
29 {
30 switch ( inputNumber )
31 {
32 case 1:
33 number1 = inputNumber;
34 break; // done processing case
35
36 case 2:
37 number2 = inputNumber;
38 break; // done processing case
39
40 case 3:
41 number3 = inputNumber;
42
43 4:
44 number4 = inputNumber;
45 break; // done processing case
46
47 case 5:
48 number5 = inputNumber;
49 break; // done processing case
50
51 counter++
52 } // end if
53 else
54 System.out.println(
55 "Invalid Input\nNumber should be between 1 and 30" );
56 } // end while
57
58 // print histograms
59 for ( counter = 1, counter >= 5, counter++ )
60 {
61 switch ( counter == 1 )
62 {
63 case 1:
64 value = number1;
65 break; // done processing case
66
67 case 2:
68 value = number2;
69 break; // done processing case
70
71 case 3:
72 value = number3;
73 break; // done processing case
74
75 case 4:
76 value = number4;
77 break; // done processing case
78
79 case 5:
80 value = number5;
81 break; // done processing case
82 }
83

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 147

Lab Exercises Name:

Debugging

84 for ( int j = 1; int j <= value; int j++ )


85 System.out.print( "*" );
86
87 System.out.println();
88 } // end for loop
89 } // end method drawHistograms
90 } // end class Graphs

1 // Debugging problem Chapter 5: GraphsTest.java


2 // Test application for class Graphs
3 public class GraphsTest
4 {
5 public static void main( String args[] )
6 {
7 Graphs application = new Graphs();
8 application.drawHistograms();
9 } // end main
10 } // end class GraphsTest

© 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.

2. Write a do…while loop that prints the integers from 10 to 0, 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

Postlab Activities Name:

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

Postlab Activities Name:

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

Postlab Activities Name:

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

Postlab Activities Name:

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:

On the first day of Christmas, my true love gave to me:


a Partridge in a pear tree.

On the second day of Christmas, my true love gave to me:


Two turtle doves, and
a Partridge in a pear tree.

On the third day of Christmas, my true love gave to me:


Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the fourth day of Christmas, my true love gave to me:


Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the fifth day of Christmas, my true love gave to me:


Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the sixth day of Christmas, my true love gave to me:


Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the seventh day of Christmas, my true love gave to me:


Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Control Statements: Part 2 155

Postlab Activities Name:

Programming Challenges

On the eighth day of Christmas, my true love gave to me:


Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the ninth day of Christmas, my true love gave to me:


Nine ladies dancing,
Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the tenth day of Christmas, my true love gave to me:


Ten drummers drumming,
Nine ladies dancing,
Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the eleventh day of Christmas, my true love gave to me:


Eleven pipers piping,
Ten drummers drumming,
Nine ladies dancing,
Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

On the twelfth day of Christmas, my true love gave to me:


Twelve lords-a-leaping,
Eleven pipers piping,
Ten drummers drumming,
Nine ladies dancing,
Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings.
Four calling birds,
Three French hens,
Two turtle doves, and
a Partridge in a pear tree.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

You might also like