control statements: part 2 - university of...

41
5 Control Statements: Part 2 OBJECTIVES In this chapter you will learn: The essentials of counter-controlled repetition. To use the for and dowhile repetition statements to execute statements in a program repeatedly. To understand multiple selection using the switch selection statement. To use the break and continue program control statements to alter the flow of control. To use the logical operators to form complex conditional expressions in control statements. Not everything that can be counted counts, and not every thing that counts can be counted. —Albert Einstein Who can control his fate? —William Shakespeare The used key is always bright. —Benjamin Franklin Intelligence … is the faculty of making artificial objects, especially tools to make tools. —Henri Bergson Every advantage in the past is judged in the light of the final issue. —Demosthenes

Upload: vantruc

Post on 11-Mar-2018

228 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

5ControlStatements: Part 2

O B J E C T I V E SIn this chapter you will learn:

■ The essentials of counter-controlled repetition.

■ To use the for and do…while repetition statements to executestatements in a program repeatedly.

■ To understand multiple selection using the switch selectionstatement.

■ To use the break and continue program control statements toalter the flow of control.

■ To use the logical operators to form complex conditionalexpressions in control statements.

Not everything that can becounted counts, and notevery thing that counts canbe counted.—Albert Einstein

Who can control his fate?—William Shakespeare

The used key is always bright.—Benjamin Franklin

Intelligence … is the facultyof making artificial objects,especially tools to make tools.—Henri Bergson

Every advantage in the pastis judged in the light of thefinal issue.—Demosthenes

Page 2: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Chapter 5 Control Statements: Part 2 153

Name: Date:

Section:

Assignment Checklist

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

Postlab Activities

Coding Exercises 1, 2, 3, 4, 5, 6, 7, 8

Programming Challenges 1, 2

Page 3: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Chapter 5 Control Statements: Part 2 155

Prelab Activities

Name: Date:

Section:

Matching

After reading Chapter 5 of Java How to Program: Seventh Edition, answer the given questions. These questionsare 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 rightcolumn.

Term Description

E

H

J

A

B

F

D

L

I

G

C

K

1. &&

2. ||

3. !

4. switch

5. continue

6. break

7. for repetition statement

8. do…while repetition statement

9. |

10. off-by-one error

11. &

12. constant

a) Handles a series of decisions, in which a particularvariable or expression is tested for values it can as-sume and different actions are taken.

b) Skips any remaining statements in the body of a rep-etition statement and proceeds with the next itera-tion of the loop.

c) Boolean logical AND

d) Handles all of the details of counter-controlled rep-etition.

e) Conditional AND.

f) Causes immediate exit from a repetition statement.

g) Can be caused by the use of an incorrect relationaloperator or using an incorrect final value of a loopcounter 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 notchange for the entire program.

l) Repetition statement that tests the loop-continua-tion condition at the end of the loop, so that thebody of the loop will execute at least once.

Page 4: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Fill in the Blank

Chapter 5 Control Statements: Part 2 157

Name: Date:

Section:

Fill in the Blank

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 true or theword false based on the expression’s value.

14. Typically, for statements are used for counter-controlled repetition and while statements are usedfor sentinel-controlled repetition.

15. In most programs, it is necessary to include a(n) break statement after the statements for each case in aswitch statement.

16. The scope of a variable defines where it can be referenced in a program by using just the variable’s name.

17. Logical 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) logic error.

19. Programs should control counting loops with integer values.

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

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

Page 5: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Short Answer

Chapter 5 Control Statements: Part 2 159

Name: Date:

Section:

Short Answer

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?

Counter-controlled repetition requires the name of a control variable, the initial value of the control variable, theincrement or decrement by which the control variable is modified each time through the loop, and the conditionthat tests for the final value of the control variable.

23. Why should programs control counting loops with integers and not with floating-point numbers?

Programs should control counting loops with integers because floating-point values may be approximate. Count-ing with floating-point values may result in imprecise counter values and inaccurate tests for termination.

24. Explain why placing a semicolon after the header of a for statement is a logic error and not a compilationerror.

Placing a semicolon after the for statement header is not a compilation error because Java treats the semicolonas an empty statement, which satisfies the requirement that the for statement have at least one statement in itsbody. This normally is a logic error because the code will compile, but will not execute correctly.

25. Differentiate between the while and the do…while repetition statements.

In a while statement the program tests the loop-continuation condition at the beginning of the loop, before per-forming the body of the loop. If the initial condition is false, the body does not execute. The do…while state-ment tests the condition after performing the body of the loop, so the body of the loop always executes at leastonce.

26. Explain why an infinite loop can occur and how one can be prevented.

An infinite loop occurs in a repetition statement when the loop-continuation condition never becomes false.In a counter-controlled loop, ensure that the control variable value is modified in a way that will eventually causethe loop-continuation condition to become false. In a sentinel-controlled loop ensure that the sentinel value iseventually input.

Page 6: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Programming Output

Chapter 5 Control Statements: Part 2 161

Name: Date:

Section:

Programming Output

For each of the given program segments, read the code and write the output in the space provided below eachprogram. [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:

27. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

28. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

1 int startingValue;2 int terminatingValue;3 int stepValue;45 for ( int i = startingValue; i < terminatingValue; i += stepValue )6 System.out.printf( "%d ", i );

1 startingValue = 0;2 terminatingValue = 5;3 stepValue = 1;

0 1 2 3 4

1 startingValue = -3;2 terminatingValue = 2;3 stepValue = 1;

-3 -2 -1 0 1

Page 7: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Programming Output

162 Control Statements: Part 2 Chapter5

29. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:No Output

30. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

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

1 startingValue = 6;2 terminatingValue = 5;3 stepValue = 1;

1 startingValue = 0;2 terminatingValue = 5;3 stepValue = 3;

0 3

1 int startingValue;2 int terminatingValue;3 int stepValue;45 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 switch30 } // end for

Page 8: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Programming Output

Chapter 5 Control Statements: Part 2 163

31. What will be the output if the following code is placed at line 4 of the preceding class definition?

Your answer:

32. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

33. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

1 startingValue = 0;2 terminatingValue = 6;3 stepValue = 2;

Hello there, How are you doing?Beautiful day isn’t it?See you later.

1 startingValue = 0;2 terminatingValue = 6;3 stepValue = 3;

Hello there, Terrific.See you later.

1 startingValue = -3;2 terminatingValue = 2;3 stepValue = 1;

See you later.See you later.See you later.Hello there, What’s up?How are you doing?

Page 9: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Programming Output

164 Control Statements: Part 2 Chapter5

34. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:

35. What will be the output if the following code is placed at line 4 of the preceding code?

Your answer:No Output

36. What is output by the following code segment?

Your answer:

1 startingValue = -5;2 terminatingValue = 1;3 stepValue = 2;

See you later.See you later.See you later.What’s up?

1 startingValue = 10;2 terminatingValue = 5;3 stepValue = 1;

1 for ( int i = 0; i <= 11; i++ )2 {3 if ( i % 2 == 0 )4 continue;56 if ( i == 11 )7 break;89 System.out.printf( "%d ", i );

10 } // end for

1 3 5 7 9

Page 10: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Correct the Code

Chapter 5 Control Statements: Part 2 165

Name: Date:

Section:

Correct the Code

Determine if there is an error in each of the following program segments. If there is an error, specify whether itis a logic error or a compilation error, circle the error in the program and write the corrected code in the spaceprovided after each problem. If the code does not contain an error, write “no error.” [Note: There may be morethan 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:

• Variable product must be initialized outside of the for loop (line 1). Logic error.

38. The following for loop should print the sum of consecutive odd and even integers in the range 1–10. Theexpected output is shown below the code.

1 for ( int i = 1; i <= 5; i++ )2 {3 int product = 1;4 product *= i;5 }

123 for ( int i = 1; i <= 5; i++ )4 product *= i;

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 = 33 + 4 = 75 + 6 = 117 + 8 = 159 + 10 = 19

int product = 1;

Page 11: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Prelab Activities Name:

Correct the Code

166 Control Statements: Part 2 Chapter5

Your answer:

• On line 1, variable j should be initialized to 2 and both i and j should be incremented by 2 after eachiteration. Logic error.

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:

• The preincrement operator on line 2 cannot be used because the expression in parentheses cannot bemodified. The line should use a simple addition statement. Compilation error.

40. The following switch statement should print either "x is 5", "x is 10" or "x is neither 5 nor 10".

Your answer:

No Error

1 for ( int i = 1, j = ; i <= 10 && j <= 10; )2 System.out.printf( "%d + %d = %d\n", i, j, ( i + j ) );

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

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

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

2 i+=2, j+=2

Page 12: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Chapter 5 Control Statements: Part 2 167

Lab Exercises

Name: Date:

Section:

Lab Exercise 1 — Triangles

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructorpresent. 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 replacedwith comments. Read the problem description and examine the output, then study the template code. Using theproblem-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 codefor the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab ObjectivesThis 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 DescriptionWrite 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 formSystem.out.print( "*" ); which causes the asterisks to print side by side. A statement of the form Sys-

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

Page 13: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 1 — Triangles

168 Control Statements: Part 2 Chapter5

Sample Output

Template

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

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

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

***

*******

***********

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

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

1 // Lab 1: Triangles.java2 // Program prints four triangles, one below the other3 public class Triangles4 {

Fig. L 5.1 | Triangles.java. (Part 1 of 2.)

Page 14: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 1 — Triangles

Chapter 5 Control Statements: Part 2 169

Problem-Solving Tips1. For the first triangle use a nested for statement in which the outer loop counts rows and the inner loopcounts 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 to1. 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.

4. For the third and fourth triangles use two separate inner loops—one for displaying spaces and one fordisplaying asterisks.

5. If you have any questions as you proceed, ask your lab instructor for assistance.

5 // draw four triangles6 public void drawTriangles()7 {8 int row; // the row position9 int column; // the column position

10 int space; // number of spaces to print1112 // first triangle13 /* Write code to display the first triangle. Use nested for loops. The14 outer loop should control which row of asterisks is being displayed.15 The inner loop should display one asterisk at a time. */1617 // second triangle18 /* Write code to display the second triangle using techniques similar to19 the first triangle */2021 // third triangle22 /* Write code to display the third triangle. The outer for loop should23 contain two separate inner for loops--one to display spaces and one to24 display asterisks. */2526 // fourth triangle27 /* Write code to display the fourth triangle using techniques similar to28 the third triangle. */29 } // end method drawTriangles30 } // end class Triangles

1 // Lab 1: TrianglesTest.java2 // Test application for class Triangles3 public class TrianglesTest4 {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

Fig. L 5.1 | Triangles.java. (Part 2 of 2.)

Page 15: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 1 — Triangles

170 Control Statements: Part 2 Chapter5

Solution

1 // Lab 1: Triangles.java2 // Program prints four triangles, one below the other3 public class Triangles4 {5 // draw four triangles6 public void drawTriangles()7 {8 int row; // the row position9 int column; // the column position

10 int space; // number of spaces to print1112 // first triangle13 for ( row = 1; row <= 10; row++ )14 {15 for ( column = 1; column <= row; column++ )16 System.out.print( "*" );1718 System.out.println();19 } // end for loop2021 System.out.println();2223 // second triangle24 for ( row = 10; row >= 1; row-- )25 {26 for ( column = 1; column <= row; column++ )27 System.out.print( "*" );2829 System.out.println();30 } // end for loop3132 System.out.println();3334 // third triangle35 for ( row = 10; row >= 1; row-- )36 {37 for ( space = 10; space > row; space-- )38 System.out.print( " " );3940 for ( column = 1; column <= row; column++ )41 System.out.print( "*" );4243 System.out.println();44 } // end for loop4546 System.out.println();4748 // fourth triangle49 for ( row = 10; row >= 1; row-- ) {5051 for ( space = 1; space < row; space++ )52 System.out.print( " " );5354 for ( column = 10; column >= row; column-- )55 System.out.print( "*" );56

Page 16: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 1 — Triangles

Chapter 5 Control Statements: Part 2 171

Follow-Up Question and Activity1. Using the techniques of the third and fourth triangles in Lab Exercise 1, display two triangles in the format

shown below.

57 System.out.println();58 } // end for loop59 } // end method drawTriangles60 } // end class Triangles

1 // Lab 1: TrianglesTest.java2 // Test application for class Triangles3 public class TrianglesTest4 {5 public static void main( String args[] )6 {7 Triangles application = new Triangles();8 application.drawTriangles();9 } // end main

10 } // end class TrianglesTest

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

********

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

1 // Lab 1: Triangles.java2 // Program prints four triangles, one below the other3 public class Triangles4 {5 // draw four triangles6 public void drawTriangles()7 {8 int row; // the row position9 int column; // the column position

10 int space; // number of spaces to print1112 // first triangle13 for ( row = 0; row <= 4; row++ )14 {15 for ( column = row; column >= 0; column-- )16 System.out.print( " " );1718 for ( column = 2 * row; column <= 8; column++ )19 System.out.print( "*" );20

Page 17: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 1 — Triangles

172 Control Statements: Part 2 Chapter5

21 System.out.println();22 } // end for loop2324 // second triangle25 for ( row = 0; row <= 4; row++ )26 {27 for ( column = row; column <= 4; column++ )28 System.out.print( " " );2930 for ( column = 2 * row; column >= 0; column-- )31 System.out.print( "*" );3233 System.out.println();34 } // end for loop35 } // end method drawTriangles36 } // end class Triangles

1 // Lab 1: TrianglesTest.java2 // Test application for class Triangles3 public class TrianglesTest4 {5 public static void main( String args[] )6 {7 Triangles application = new Triangles();8 application.drawTriangles();9 } // end main

10 } // end class TrianglesTest

Page 18: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

Chapter 5 Control Statements: Part 2 173

Name: Date:

Section:

Lab Exercise 2 — Sales

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructorpresent. 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 replacedwith comments. Read the problem description and examine the output, then study the template code. Using theproblem-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 codefor the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab ObjectivesThis 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 DescriptionAmail-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 numbersas follows:

a) product number

b) quantity sold

Your program should use a switch statement to determine the retail price for each product. It should calculateand 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.

Page 19: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

174 Control Statements: Part 2 Chapter5

Sample Output

Template

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

Product 1: $14.90Product 2: $0.00Product 3: $0.00Product 4: $0.00Product 5: $68.70

1 // Lab 2: Sales.java2 // Program calculates sales, based on an input of product3 // number and quantity sold4 import java.util.Scanner;56 public class Sales7 {8 // calculates sales for 5 products9 public void calculateSales()

10 {11 Scanner input = new Scanner( System.in );1213 double product1 = 0; // amount sold of first product14 double product2 = 0; // amount sold of second product15 double product3 = 0; // amount sold of third product16 double product4 = 0; // amount sold of fourth product17 double product5 = 0; // amount sold of fifth product1819 /* Ask the user to enter product number */2021 /* Create while statement that loops until sentinel is entered */2223 /* Determine whether user’s product number is in 1-5 */2425 /* If so, ask user to input the quantity sold */2627 /* Write a switch statement here that will compute the total28 for that product */2930 /* If product number is not in 1-5, test if product number is not 0 */31 /* Display error message for invalid product number */3233 /* Ask the user to enter another product number */3435 /* end while loop */3637 // print summary38 System.out.println();39 System.out.printf( "Product 1: $%.2f\n", product1 );

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

Page 20: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

Chapter 5 Control Statements: Part 2 175

Problem-Solving Tips1. 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 enteredis 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 onthe 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 eachcontrol 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.

Solution

40 /* write code here for the rest of the summary message it should contain41 the totals for the rest of the products, each on it’s own line */42 } // end method calculateSales43 } // end class Sales

1 // Lab 2: SalesTest.java2 // Test application for class Sales3 public class SalesTest4 {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

1 // Lab 2: Sales.java2 // Program calculates sales, based on an input of product3 // number and quantity sold4 import java.util.Scanner;56 public class Sales7 {8 // calculates sales for 5 products9 public void calculateSales()

10 {11 Scanner input = new Scanner( System.in );1213 double product1 = 0; // amount sold of first product14 double product2 = 0; // amount sold of second product15 double product3 = 0; // amount sold of third product

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

Page 21: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

176 Control Statements: Part 2 Chapter5

16 double product4 = 0; // amount sold of fourth product17 double product5 = 0; // amount sold of fifth product1819 System.out.print( "Enter product number (1-5) (0 to stop): " );20 int productId = input.nextInt();2122 // ask user for product number until flag value entered23 while ( productId != 0 )24 {25 if ( productId >= 1 && productId <= 5 )26 {27 // determine the number sold of the item28 System.out.print( "Enter quantity sold: " );29 int quantity = input.nextInt();3031 // increment the total for the item by the32 // price times the quantity sold33 switch ( productId )34 {35 case 1:36 product1 += quantity * 2.98;37 break;3839 case 2:40 product2 += quantity * 4.50;41 break;4243 case 3:44 product3 += quantity * 9.98;45 break;4647 case 4:48 product4 += quantity * 4.49;49 break;5051 case 5:52 product5 += quantity * 6.87;53 break;54 } // end switch55 } // end if56 else if ( productId != 0 )57 System.out.println(58 "Product number must be between 1 and 5 or 0 to stop" );5960 System.out.print( "Enter product number (1-5) (0 to stop): " );61 productId = input.nextInt();62 } // end while loop6364 // print summary65 System.out.println();66 System.out.printf( "Product 1: $%.2f\n", product1 );67 System.out.printf( "Product 2: $%.2f\n", product2 );68 System.out.printf( "Product 3: $%.2f\n", product3 );69 System.out.printf( "Product 4: $%.2f\n", product4 );70 System.out.printf( "Product 5: $%.2f\n", product5 );71 } // end method calculateSales72 } // end class Sales

Page 22: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

Chapter 5 Control Statements: Part 2 177

Follow-Up Questions and Activities1. 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?

In the original program, if the user enters a number other than 1-5 or 0, a message appears that informsthe user to enter a valid number. This is because of the while loop that runs until a valid number has beenentered.

2. Modify the program so that there is a sixth product, priced at $20.00, that represents a package of all theproducts. For each of the packages purchased, add $4.00 to the totals for all the other products. Do not keeptrack of the packages separately.

1 // Lab 2: SalesTest.java2 // Test application for class Sales3 public class SalesTest4 {5 public static void main( String args[] )6 {7 Sales application = new Sales();8 application.calculateSales();9 } // end main

10 } // end class SalesTest

1 // Lab 2: Sales.java2 // Program calculates sales, based on an input of product3 // number and quantity sold4 import java.util.Scanner;56 public class Sales7 {8 // calculates sales for 5 products9 public void calculateSales()

10 {11 Scanner input = new Scanner( System.in );1213 double product1 = 0; // amount sold of first product14 double product2 = 0; // amount sold of second product15 double product3 = 0; // amount sold of third product16 double product4 = 0; // amount sold of fourth product17 double product5 = 0; // amount sold of fifth product1819 System.out.print( "Enter product number (1-6) (0 to stop): " );20 int productId = input.nextInt();2122 // ask user for product number until flag value entered23 while ( productId != 0 )24 {25 if ( productId >= 1 && productId <= 6 )26 {27 // determine the number sold of the item28 System.out.print( "Enter quantity sold: " );29 int quantity = input.nextInt();30

Page 23: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

178 Control Statements: Part 2 Chapter5

31 // increment the total for the item by the32 // price times the quantity sold33 switch ( productId )34 {35 case 1:36 product1 += quantity * 2.98;37 break;3839 case 2:40 product2 += quantity * 4.50;41 break;4243 case 3:44 product3 += quantity * 9.98;45 break;4647 case 4:48 product4 += quantity * 4.49;49 break;5051 case 5:52 product5 += quantity * 6.87;53 break;5455 case 6:56 product1 += quantity * 4;57 product2 += quantity * 4;58 product3 += quantity * 4;59 product4 += quantity * 4;60 product5 += quantity * 4;61 break;62 } // end switch63 } // end if64 else if ( productId != 0 )65 System.out.println(66 "Product number must be between 1 and 6 or 0 to stop" );6768 System.out.print( "Enter product number (1-6) (0 to stop): " );69 productId = input.nextInt();70 } // end while loop7172 // print summary73 System.out.println();74 System.out.printf( "Product 1: $%.2f\n", product1 );75 System.out.printf( "Product 2: $%.2f\n", product2 );76 System.out.printf( "Product 3: $%.2f\n", product3 );77 System.out.printf( "Product 4: $%.2f\n", product4 );78 System.out.printf( "Product 5: $%.2f\n", product5 );79 } // end method calculateSales80 } // end class Sales

Page 24: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 2 — Sales

Chapter 5 Control Statements: Part 2 179

1 // Lab 2: SalesTest.java2 // Test application for class Sales3 public class SalesTest4 {5 public static void main( String args[] )6 {7 Sales application = new Sales();8 application.calculateSales();9 } // end main

10 } // end class SalesTest

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

Product 1: $22.90Product 2: $8.00Product 3: $8.00Product 4: $8.00Product 5: $76.70

Page 25: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Chapter 5 Control Statements: Part 2 181

Name: Date:

Section:

Lab Exercise 3 — Pythagorean Triples

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructorpresent. 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 replacedwith comments. Read the problem description and examine the output, then study the template code. Using theproblem-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 codefor the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab ObjectivesThis 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 DescriptionA right triangle can have sides whose lengths are all integers. The set of three integer values for the lengths of thesides of a right triangle is called a Pythagorean triple. The lengths of the three sides must satisfy the relationshipthat the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an application tofind all Pythagorean triples for side1, side2 and the hypotenuse, all no larger than 500. Use a triple-nested forloop that tries all possibilities. This method is an example of “brute-force” computing. You will learn in moreadvanced computer science courses that there are large numbers of interesting problems for which there is noknown algorithmic approach other than using sheer brute force.

Page 26: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

182 Control Statements: Part 2 Chapter5

Sample Output

Template

Solution

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25

.

.

.

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

1 // Lab 3: Triples.java2 // Program calculates Pythagorean triples3 public class Triples4 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;1112 /* Write loop for side1 to try the values 1-500. */1314 /* Write loop for side2 to try the values 1-500. */1516 /* Write loop for hypotenuse to try the values 1-500 */1718 /* Write an if statement that determines whether the sum of the19 two sides squared equals the hypotenuse squared. If this20 condition is true display side1, side2 and hypotenuse. */21 } // end main22 } // end class Triples

Fig. L 5.5 | Triples.java.

1 // Lab 3: Triples.java2 // Program calculates Pythagorean triples3 public class Triples4 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;

Page 27: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Chapter 5 Control Statements: Part 2 183

Problem-Solving Tips1. This program does not require any input from the user.

2. The formula for the Pythagorean Theorem is hypotenuse2 = side12 + side22.

3. Do not be concerned about trying values that do not make sense, such as a 1-500-1 triangle. Brute-forcecomputing techniques try all possible values.

4. Use an if statement to determine whether the sum of the two squared sides is equal to the hypotenusesquared. If so, output side1, side2 and hypotenuse.

5. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Questions and Activities1. 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 val-ue.

9 int side2;10 int hypotenuse;1112 for ( side1 = 1; side1 <= 500; side1++ )1314 for ( side2 = 1; side2 <= 500; side2++ )1516 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )1718 // use Pythagorean Theorem to print right triangles19 if ( ( side1 * side1 ) + ( side2 * side2 ) ==20 ( hypotenuse * hypotenuse ) )21 System.out.printf( "s1: %d, s2: %d, h: %d\n",22 side1, side2, hypotenuse );23 } // end main24 } // end class Triples

1 // Lab 3: Triples.java2 // Program calculates Pythagorean triples3 public class Triples4 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;11 int counter = 0;1213 for ( side1 = 1; side1 <= 500; side1++ )1415 for ( side2 = 1; side2 <= 500; side2++ )1617 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )18 {19 counter++;20

Page 28: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

184 Control Statements: Part 2 Chapter5

2. Add a break statement to the program inside the innermost for loop. This break statement should executeafter the twentieth Pythagorean triple is found. Explain what happens to the program after the 20th tripleis found. Do all three for loops exit, or just the innermost one? What happens differently when the breakstatement is placed inside the second loop? What happens differently when the break statement is placedinside the outermost loop? [Hint: Use the loop counter you defined in the previous follow-up question tocount how many times the loops execute.]

Break in innermost for loop:

21 // use Pythagorean Theorem to print right triangles22 if ( ( side1 * side1 ) + ( side2 * side2 ) ==23 ( hypotenuse * hypotenuse ) )24 System.out.printf( "s1: %d, s2: %d, h: %d\n",25 side1, side2, hypotenuse );26 } // end for2728 System.out.printf( "The inner loop iterated %d times.\n", counter );29 } // end main30 } // end class Triples

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25

.

.

.

s1: 480, s2: 31, h: 481s1: 480, s2: 88, h: 488s1: 480, s2: 108, h: 492s1: 480, s2: 140, h: 500s1: 483, s2: 44, h: 485The inner loop iterated 125000000 times.

1 // Lab 3: Triples1.java2 // Program calculates Pythagorean triples3 public class Triples14 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;11 int counter = 0;12 int numberOfTriples = 0;1314 for ( side1 = 1; side1 <= 500; side1++ )1516 for ( side2 = 1; side2 <= 500; side2++ )1718 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )19 {

Page 29: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Chapter 5 Control Statements: Part 2 185

Break in second for loop:

20 if ( numberOfTriples >= 20 )21 break;2223 counter++;2425 // use Pythagorean Theorem to print right triangles26 if ( ( side1 * side1 ) + ( side2 * side2 ) ==27 ( hypotenuse * hypotenuse ) )28 {29 System.out.printf( "s1: %d, s2: %d, h: %d\n",30 side1, side2, hypotenuse );31 numberOfTriples++;32 } // end if33 } // end for3435 System.out.printf( "The inner loop iterated %d times.\n", counter );36 } // end main37 } // end class Triples1

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25s1: 8, s2: 6, h: 10s1: 8, s2: 15, h: 17s1: 9, s2: 12, h: 15s1: 9, s2: 40, h: 41s1: 10, s2: 24, h: 26s1: 11, s2: 60, h: 61s1: 12, s2: 5, h: 13s1: 12, s2: 9, h: 15s1: 12, s2: 16, h: 20s1: 12, s2: 35, h: 37s1: 13, s2: 84, h: 85s1: 14, s2: 48, h: 50s1: 15, s2: 8, h: 17s1: 15, s2: 20, h: 25s1: 15, s2: 36, h: 39The inner loop iterated 3517539 times.

1 // Lab 3: Triples2.java2 // Program calculates Pythagorean triples3 public class Triples24 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;11 int counter = 0;12 int numberOfTriples = 0;

Page 30: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

186 Control Statements: Part 2 Chapter5

1314 for ( side1 = 1; side1 <= 500; side1++ )1516 for ( side2 = 1; side2 <= 500; side2++ )17 {18 if ( numberOfTriples >= 20 )19 break;2021 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )22 {23 counter++;2425 // use Pythagorean Theorem to print right triangles26 if ( ( side1 * side1 ) + ( side2 * side2 ) ==27 ( hypotenuse * hypotenuse ) )28 {29 System.out.printf( "s1: %d, s2: %d, h: %d\n",30 side1, side2, hypotenuse );31 numberOfTriples++;32 } // end if33 } // end inner for34 } // end middle for3536 System.out.printf( "The inner loop iterated %d times.\n", counter );37 } // end main38 } // end class Triples2

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25s1: 8, s2: 6, h: 10s1: 8, s2: 15, h: 17s1: 9, s2: 12, h: 15s1: 9, s2: 40, h: 41s1: 10, s2: 24, h: 26s1: 11, s2: 60, h: 61s1: 12, s2: 5, h: 13s1: 12, s2: 9, h: 15s1: 12, s2: 16, h: 20s1: 12, s2: 35, h: 37s1: 13, s2: 84, h: 85s1: 14, s2: 48, h: 50s1: 15, s2: 8, h: 17s1: 15, s2: 20, h: 25s1: 15, s2: 36, h: 39The inner loop iterated 3518000 times.

Page 31: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Chapter 5 Control Statements: Part 2 187

Break in outermost for loop:

1 // Lab 3: Triples3.java2 // Program calculates Pythagorean triples3 public class Triples34 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;11 int counter = 0;12 int numberOfTriples = 0;1314 for ( side1 = 1; side1 <= 500; side1++ )15 {16 if ( numberOfTriples >= 20 )17 break;1819 for ( side2 = 1; side2 <= 500; side2++ )2021 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )22 {23 counter++;2425 // use Pythagorean Theorem to print right triangles26 if ( ( side1 * side1 ) + ( side2 * side2 ) ==27 ( hypotenuse * hypotenuse ) )28 {29 System.out.printf( "s1: %d, s2: %d, h: %d\n",30 side1, side2, hypotenuse );31 numberOfTriples++;32 } // end if33 } // end inner for34 } // end outer for3536 System.out.printf( "The inner loop iterated %d times.\n", counter );37 } // end main38 } // end class Triples3

Page 32: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

188 Control Statements: Part 2 Chapter5

The break statement placed inside the innermost loop will exit the innermost loop, but not the outer twoloops. Those two loops will continue to run, but no processing of triples will occur. The innermost loopwill execute exactly enough times to find 20 triples. When the break statement is placed in the secondloop, the innermost loop will finish its 500 iterations even after finding the twentieth triple. After the firsttime the second loop is reached after the twentieth triple is found, no more processing of triples will occur.When the break statement is placed in the outermost loop, both inner loop will have to complete after thetwentieth triple is found. Only after these two loops complete will the break statement be reached.

3. Add a continue statement to the program that prevents a Pythagorean triple from being found when side1is equal to 8. Using the loop counter again from Follow-Up Question 1, calculate how many times this newprogram executed the innermost for loop. Explain how the continue statement affected the output.

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25s1: 8, s2: 6, h: 10s1: 8, s2: 15, h: 17s1: 9, s2: 12, h: 15s1: 9, s2: 40, h: 41s1: 10, s2: 24, h: 26s1: 11, s2: 60, h: 61s1: 12, s2: 5, h: 13s1: 12, s2: 9, h: 15s1: 12, s2: 16, h: 20s1: 12, s2: 35, h: 37s1: 13, s2: 84, h: 85s1: 14, s2: 48, h: 50s1: 15, s2: 8, h: 17s1: 15, s2: 20, h: 25s1: 15, s2: 36, h: 39s1: 15, s2: 112, h: 113The inner loop iterated 3750000 times.

1 // Lab 3: Triples.java2 // Program calculates Pythagorean triples3 public class Triples4 {5 public static void main( String args[] )6 {7 // declare the three sides of a triangle8 int side1;9 int side2;

10 int hypotenuse;11 int counter = 0;1213 for ( side1 = 1; side1 <= 500; side1++ )14 {15 if ( side1 == 8 )16 continue;1718 for ( side2 = 1; side2 <= 500; side2++ )19

Page 33: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Lab Exercises Name:

Lab Exercise 3 — Pythagorean Triples

Chapter 5 Control Statements: Part 2 189

The continue statement affects the output by skipping an iteration of the outer for loop. This results in250,000 (500 * 500) less iterations of the inner loop.

20 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ )21 {22 counter++;2324 // use Pythagorean Theorem to print right triangles25 if ( ( side1 * side1 ) + ( side2 * side2 ) ==26 ( hypotenuse * hypotenuse ) )27 System.out.printf( "s1: %d, s2: %d, h: %d\n",28 side1, side2, hypotenuse );29 } // end inner for30 } // end outer for3132 System.out.printf( "The inner loop iterated %d times.\n", counter );33 } // end main34 } // end class Triples

s1: 3, s2: 4, h: 5s1: 4, s2: 3, h: 5s1: 5, s2: 12, h: 13s1: 6, s2: 8, h: 10s1: 7, s2: 24, h: 25

.

.

.

s1: 480, s2: 31, h: 481s1: 480, s2: 88, h: 488s1: 480, s2: 108, h: 492s1: 480, s2: 140, h: 500s1: 483, s2: 44, h: 485The inner loop iterated 124750000 times.

Page 34: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Chapter 5 Control Statements: Part 2 197

Postlab Activities

Name: Date:

Section:

Coding Exercises

These coding exercises reinforce the lessons learned in the lab and provide additional programming experienceoutside the classroom and laboratory environment. They serve as a review after you have successfully completedthe 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 thatcorresponds to the number (i.e., 1 is A, 2 is B, etc.).

1 for ( int i = 1; i <= 100; i++ )23 if ( i % 2 == 1 )4 printf( "%d ", i );

1 int i = 10;23 do4 {5 printf( "%d ", i );6 i--;7 } while ( i >= 0 );

1 for ( int i = 1; i <= 5; i++ )2 {3 switch ( i )4 {5 case 1:6 printf( "A" );7 break;89 case 2:

10 printf( "B" );11 break;1213 case 3:14 printf( "C" );15 break;16

Page 35: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Coding Exercises

198 Control Statements: Part 2 Chapter5

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.

17 case 4:18 printf( "D" );19 break;2021 case 5:22 printf( "E" );23 break;24 } // end switch25 } // end for

1 int i = 1;2 int sum = 0;34 while ( i <= 10 )5 {6 if ( i == 3 || i == 6 )7 continue;89 sum += i

10 i++;11 } // end while1213 printf( "sum: %d\n", sum );

1 for ( int i = 1; i <= 10; i++ )2 {3 if ( i == 6 )4 break;56 printf( "%d ", i );7 } // end for

1 for ( int i = 1; i <= 10; i++ )2 {3 if ( i == 6 )4 continue;56 printf( "%d ", i );7 } // end for

Page 36: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Coding Exercises

Chapter 5 Control Statements: Part 2 199

7. Modify your solution in Coding Exercise 6 to use a while statement instead of a for statement.

8. Modify your solution in Coding Exercise 7 to use a do…while statement instead of a while statement.

1 int i = 1;23 while ( i <= 10 )4 {5 if ( i == 6 )6 continue;78 printf( "%d ", i );9 i++;

10 } // end while

1 int i = 1;23 do4 {5 if ( i == 6 )6 continue;78 printf( "%d ", i );9 i++;

10 } while ( i <= 10 )

Page 37: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Programming Challenges

202 Control Statements: Part 2 Chapter5

2. (“The Twelve Days of Christmas” Song) Write an application that uses repetition and switch statements toprint 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 thesong.

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 willbe 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, anda Partridge in a pear tree.

On the third day of Christmas, my true love gave to me:Three French hens,Two turtle doves, anda 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, anda 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, anda 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, anda 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, anda Partridge in a pear tree.

Page 38: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Programming Challenges

Chapter 5 Control Statements: Part 2 203

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, anda 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, anda 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, anda 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, anda 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, anda Partridge in a pear tree.

Page 39: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Programming Challenges

204 Control Statements: Part 2 Chapter5

Solution

1 // Programming Challenge 2: Twelve.java2 // Program prints the 12 days of Christmas song.3 public class Twelve4 {5 // print the 12 days of Christmas song6 public void printSong()7 {8 for ( int day = 1; day <= 12; day++ )9 {

10 System.out.print( "On the " );1112 // add correct day to String13 switch ( day )14 {15 case 1:16 System.out.print( "first" );17 break;1819 case 2:20 System.out.print( "second" );21 break;2223 case 3:24 System.out.print( "third" );25 break;2627 case 4:28 System.out.print( "fourth" );29 break;3031 case 5:32 System.out.print( "fifth" );33 break;3435 case 6:36 System.out.print( "sixth" );37 break;3839 case 7:40 System.out.print( "seventh" );41 break;4243 case 8:44 System.out.print( "eighth" );45 break;4647 case 9:48 System.out.print( "ninth" );49 break;5051 case 10:52 System.out.print( "tenth" );53 break;54

Page 40: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Programming Challenges

Chapter 5 Control Statements: Part 2 205

55 case 11:56 System.out.print( "eleventh" );57 break;5859 case 12:60 System.out.print( "twelfth" );61 break;62 } // end switch6364 System.out.println(65 " day of Christmas, my true love gave to me:" );6667 // add remainder of verse to String68 switch ( day )69 {70 case 12:71 System.out.println( "Twelve lords-a-leaping," );7273 case 11:74 System.out.println( "Eleven pipers piping," );7576 case 10:77 System.out.println( "Ten drummers drumming," );7879 case 9:80 System.out.println( "Nine ladies dancing," );8182 case 8:83 System.out.println( "Eight maids-a-milking," );8485 case 7:86 System.out.println( "Seven swans-a-swimming," );8788 case 6:89 System.out.println( "Six geese-a-laying," );9091 case 5:92 System.out.println( "Five golden rings." );9394 case 4:95 System.out.println( "Four calling birds," );9697 case 3:98 System.out.println( "Three French hens," );99100 case 2:101 System.out.println( "Two turtle doves, and" );102103 case 1:104 System.out.println( "a Partridge in a pear tree." );105 } // end switch106107 System.out.println();108 } // end for109 } // end method printSong110 } // end class Twelve

Page 41: Control Statements: Part 2 - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh5Ctrls2.pdf · Control Statements: Part 2 ... Exercises Assigned: Circle

Postlab Activities Name:

Programming Challenges

206 Control Statements: Part 2 Chapter5

1 // Programming Challenge 2: TwelveTest.java2 // Test application for class Twelve3 public class TwelveTest4 {5 public static void main( String args[] )6 {7 Twelve application = new Twelve();8 application.printSong();9 } // end main

10 } // end class TwelveTest