jhtp7lm im 04.fm - university of...

52
4 Control Statements: Part 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of top-down, stepwise refinement. To use the if and ifelse selection statements to choose among alternative actions. To use the while repetition statement to execute statements in a program repeatedly. To use counter-controlled repetition and sentinel-controlled repetition. To use the assignment, increment and decrement operators. Let’s all move one place on. —Lewis Carroll The wheel is come full circle. —William Shakespeare How many apples fell on Newton’s head before he took the hint! —Robert Frost All the evolution we know of proceeds from the vague to the definite. —Charles Sanders Peirce

Upload: hathien

Post on 27-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

4ControlStatements: Part 1

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

■ To use basic problem-solving techniques.

■ To develop algorithms through the process of top-down, stepwiserefinement.

■ To use the if and if…else selection statements to chooseamong alternative actions.

■ To use the while repetition statement to execute statements in aprogram repeatedly.

■ To use counter-controlled repetition and sentinel-controlledrepetition.

■ To use the assignment, increment and decrement operators.

Let’s all move one place on.—Lewis Carroll

The wheel is come full circle.—William Shakespeare

How many apples fell onNewton’s head before he tookthe hint!—Robert Frost

All the evolution we know ofproceeds from the vague tothe definite.—Charles Sanders Peirce

Chapter 4 Control Statements: Part 1 99

Name: Date:

Section:

Assignment Checklist

Exercises Assigned: Circle assignments Date Due

Prelab Activities

Matching YES NO

Fill in the Blank YES NO

Short Answer YES NO

Programming Output YES NO

Correct the Code YES NO

Lab Exercises

Exercise 1 — Credit YES NO

Follow-Up Questions and Activities 1, 2

Exercise 2 — Palindromes YES NO

Follow-Up Question and Activity 1

Exercise 3 — Largest Number YES NO

Follow-Up Question and Activity 1

Debugging YES NO

Postlab Activities

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

Programming Challenges 1, 2

Chapter 4 Control Statements: Part 1 101

Prelab Activities

Name: Date:

Section:

Matching

After reading Chapter 4 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

M

I

A

K

H

O

P

C

E

Q

G

D

B

F

J

L

N

1. --

2. ++

3. ?:

4. algorithm

5. selection statement

6. sentinel-controlled repetition

7. ;

8. pseudocode

9. repetition statement

10. counter-controlled repetition

11. program control

12. top-down, stepwise refinement

13. if

14. if…else

15. block

16. +=, -=, *=, /=, %=

17. primitive types

a) Java’s only ternary operator.

b) A selection statement that executes an indicated actiononly when the condition is true.

c) An artificial and informal language that helps program-mers develop algorithms.

d) A process for refining pseudocode by maintaining acomplete program representation for each refinement.

e) Allows the programmer to specify that an action is to berepeated while some condition remains true.

f) A selection statement that specifies separate actions toexecute when a condition is true and when a conditionis false.

g) Specifying the order in which statements are to be exe-cuted in a computer program.

h) Chooses among alternative courses of action in a pro-gram.

i) Increment operator.

j) A set of statements contained within a pair of braces.

k) A procedure for solving a problem in terms of the ac-tions to execute and the order in which the actionsshould execute.

l) Arithmetic assignment operators.

m) Decrement operator.

n) Building blocks for more complicated types in Java.

o) Used when the number of repetitions is not known be-fore the loop begins executing.

p) Empty statement.

q) Used when the number of repetitions is known beforethe loop begins executing.

Prelab Activities Name:

Fill in the Blank

Chapter 4 Control Statements: Part 1 103

Name: Date:

Section:

Fill in the Blank

Fill in the blanks for each of the following statements:

18. Specifying the order in which statements execute in a computer program is called program control .

19. The if selection statement executes an indicated action only when the condition is true.

20. Top-down, stepwise refinement is a process for refining pseudocode by maintaining a complete represen-tation of the program during each refinement.

21. Java requires all variables to have a type before they can be used in a program. For this reason, Java is referredto as a(n) strongly typed language.

22. Java uses internationally recognized standards for both characters and floating-point numbers.

23. A(n) declaration specifies the type and name of a variable.

24. The if…else selection statement specifies separate actions to execute when the condition is true andwhen the condition is false.

25. The ++ operator and the -- operator increment and decrement a variable by 1, respectively.

26. Unary cast operator ( double ) creates a temporary double-precision, floating-point copy of its oper-and.

27. A value that contains a fractional part is referred to as a floating-point number and is represented by the typesfloat or double .

Prelab Activities Name:

Short Answer

Chapter 4 Control Statements: Part 1 105

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.

28. Explain the purpose of a selection statement.

Selection statements choose among alternative actions in a program. They check for certain conditions in a pro-gram, and perform different tasks if those conditions are met.

29. Use pseudocode or a UML activity diagram to give an example of sequence control statements.

Add this grade into the running totalAdd one to the grade counter

30. Describe the term “algorithm” and why pseudocode can help programmers develop algorithms.

An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which theactions should execute. Pseudocode helps in the development of algorithms because it forces you to “think out”a program during the design process, then you can translate the pseudocode into Java code.

31. Use pseudocode or a UML activity diagram to give an example of an if…else selection statement.

If student’s grade is greater than or equal to 60Print “Passed”

ElsePrint “Failed”

32. Explain the difference between the if selection statement and the if…else selection statement.

The if selection statement performs an indicated action only when the given condition evaluates to true, oth-erwise the action is skipped. The if…else selection statement allows an action to be performed when the condi-tion is true, and a separate action if the condition is false.

33. Use pseudocode to give an example of a looping construct in which the number of repetitions is known inadvance.

While student counter is less than or equal to 10Prompt the user to enter the next exam result

Prelab Activities Name:

Short Answer

106 Control Statements: Part 1 Chapter4

Input the next exam resultAdd the grade to the running totalAdd one to student counter

34. Use pseudocode to give an example of a looping construct in which the number of repetitions is not knownin advance.

Prompt the user to enter the first gradeInput the first grade (possibly the sentinel)

While the user has not yet entered the sentinelAdd this grade into the running totalAdd one to the grade counterPrompt the user to enter the next gradeInput the next grade (possibly the sentinel)

35. Explain how repetition statements are used.

Repetition statements specify that an action (or set of actions) should be performed repeatedly while a conditionremains true.

36. Explain the difference between counter-controlled and sentinel-controlled repetition.

Counter-controlled repetition is used when the number of repetitions is known in advance. Sentinel-controlledrepetition is used when the number of repetitions is not known in advance. In this case, a sentinel value specifieswhen the repetition should terminate.

Prelab Activities Name:

Programming Output

Chapter 4 Control Statements: Part 1 107

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 questions 37–39 assume the following class definition:

37. What will be output by lines 11–14 if the user enters the integer 2 at line 9?

Your answer:

38. What will be output by lines 11–14 if the user enters the integer 3 at line 9?

Your answer:

39. What will be the output if the following code is placed at line 10 of the preceding class definition? Assumethat the user enters 5.

1 public class Test22 {3 public static void main( String args[] )4 {5 Scanner input = new Scanner();6 int number1;78 System.out.println( "Enter an integer:" );9 number1 = input.nextInt();

1011 if ( number1 % 2 == 0 )12 System.out.println( "%d is even\n", number1 );13 else14 System.out.println( "%d is odd\n", number1 );15 } // end main16 } // end class Test2

2 is even

3 is odd

1 number1 = number1 + 3;

Prelab Activities Name:

Programming Output

108 Control Statements: Part 1 Chapter4

Your answer:

40. What is output by the following program?

Your answer:

For questions 41–43, assume the following class declaration:

8 is even

1 public class Grade2 {3 public static void main( String args[] )4 {5 int grade1 = 65;6 int grade2 = 50;78 System.out.println( grade1 >= 60 ? "Passed." : "Failed." );9 System.out.println( grade2 >= 60 ? "Passed." : "Failed." );

10 } // end main11 } // end class Grade

PassedFailed

1 public class Value2 {3 public static void main( String args[] )4 {5 int x;6 int xLimit;78 /* assign values to x and xLimit here */9

10 while ( x <= xLimit )11 {12 x++;13 System.out.printf( "The value of x is %d\n", x );14 } // end while1516 System.out.printf( "The final value of x is %d\n", x );17 } // end main18 } // end class Value

Prelab Activities Name:

Programming Output

Chapter 4 Control Statements: Part 1 109

41. What will be the output if the following code is placed at line 8 of the class?

Your answer:

42. What will be the output if the following code is placed at line 8 of the class?

Your answer:

43. What will be the output if the following code is placed at line 8 of the class?

Your answer:

1 x = 1;2 xLimit = 5;

The value of x is 2

The value of x is 3

The value of x is 4

The value of x is 5

The value of x is 6

The final value of x is 6

1 x = 1;2 xLimit = -2;

The final value of x is 1

1 x = 10;2 xLimit = 5;

The final value of x is 10

Prelab Activities Name:

Programming Output

110 Control Statements: Part 1 Chapter4

For questions 44–46, assume the following class declaration:

44. What will be the output if the following code is placed at line 8 of the class?

Your answer:

45. What will be the output if the following code is placed at line 8 of the class?

Your answer:(no output)

1 public class Value2 {3 public static void main( String args[] )4 {5 int x;6 int xLimit;78 /* assign values to x and xLimit here */9

10 while ( x <= xLimit )11 {12 x++;1314 if ( x % 2 == 0 )15 System.out.printf( "%d is even.\n", x );16 else17 System.out.printf( "%d is odd.\n", x );18 } // end while19 } // end main20 } // end class Value

1 x = 0;2 xLimit = 10;

1 is odd.2 is even.3 is odd.4 is even.5 is odd.6 is even.7 is odd.8 is even.9 is odd.10 is even.11 is odd.

1 x = 02 xLimit = -2;

Prelab Activities Name:

Programming Output

Chapter 4 Control Statements: Part 1 111

46. What will be the output if the following code is placed at line 8 of the class?

Your answer:(no output)

1 x = 10;2 xLimit = 5;

Prelab Activities Name:

Correct the Code

Chapter 4 Control Statements: Part 1 113

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

47. The following segment of code should calculate whether a student has a passing grade. If so, the code shouldprint "Passed." Otherwise, the code should print "Failed." and "You must take this course again."

Your answer:

• Missing braces before line 4 and after line 5. Logic error.

48. The following while loop should compute the product of all the integers between 1 and 5, inclusive.

1 if ( grade >= 60 )2 System.out.println( "Passed." );3 else4 System.out.println( "Failed." );5 System.out.println( "You must take this course again." );

1 if ( grade >= 60 )2 System.out.println( "Passed." );3 else45 System.out.println( "Failed." );6 System.out.println( "You must take this course again." );7

1 int i = 1;2 int product = 1;34 while ( i <= 5 );5 product *= i;

{

}

Prelab Activities Name:

Correct the Code

114 Control Statements: Part 1 Chapter4

Your answer:

• The value of variable i is not incremented in the while loop. Logic error.

• The semicolon after the while loop’s header must be removed. Logic error.

49. The following while loop should print all the even integers between 0 and 20, inclusive.

Your answer:

• Missing braces on lines 4 and 9. Variable imust be incremented within the while loop or the programwill enter an infinite loop. Logic error.

50. The following while loop should print the numbers 0 through 5, inclusive.

1 int i = 1;2 int product = 1;34 while ( i <= 5 );56 product *= i;78

1 int i = 0;23 while ( i <= 20 )45 if ( i % 2 = 0 )6 System.out.printf( "%d ", i );78 i++

1 int i = 0;23 while ( i <= 20 )45 if ( i % 2 = 0 )6 System.out.printf( "%d ", i );78 i++9

1 int i = 0;23 while ( i < 5 )4 {5 System.out.printf( "%d ", i );6 i++;7 }

{

i++;}

{

}

Prelab Activities Name:

Correct the Code

Chapter 4 Control Statements: Part 1 115

Your answer:

• The if statement on line 3 should use the <= operator. Otherwise, the loop will not print i when it isequal to 5. Logic error.

51. The following while loop should print the even numbers from 20 down through 0, inclusive.

Your answer:

• Variable i should be decremented on line 8. If the value is incremented, the program will enter an in-finite loop. Logic error.

1 int i = 0;23 while ( i 5 )4 {5 System.out.printf( "%d ", i );6 i++;7 }

1 int i = 20;23 while ( i >= 0 )4 {5 if ( i % 2 == 0 )6 System.out.printf( "%d ", i );78 i++;9 }

10

1 int i = 20;23 while ( i >= 0 )4 {5 if ( i % 2 == 0 )6 System.out.printf( "%d ", i );789 }

10

<=

i--;

Prelab Activities Name:

Correct the Code

116 Control Statements: Part 1 Chapter4

52. The following while loop should print the sum of the integers between 0 and 5, inclusive.

Your answer:

• Variable i must be declared and initialized on line 2. Compilation error.

53. The following while loop should print the sum of the odd integers between 0 and 15, inclusive.

1 int sum = 0;23 while ( i <= 5 )4 {5 sum += i;6 i++;7 }89 System.out.printf( "The sum is: %d\n", sum );

1 int sum = 0;234 while ( i <= 5 )5 {6 sum += i;7 i++;8 }9

10 System.out.printf( "The sum is: %d\n", sum );

1 int sum = 0, i = 0;23 while ( i < 15 )4 {5 if ( i % 2 != 0 )6 sum += i;78 i++;9 }

1011 System.out.printf( "The sum is: %d\n", sum );

int i = 0;

Prelab Activities Name:

Correct the Code

Chapter 4 Control Statements: Part 1 117

Your answer:

• The while loop should use the <= operator on line 3 so that the loop runs when i is equal to 15. Logicerror.

54. The following while loop should print the product of the odd integers between 0 and 10, inclusive.

Your answer:

• The program should multiply product by i during each iteration of the while loop. The while loopshould then increment i. Logic error.

1 int sum = 0, i = 0;23 while ( i 15 )4 {5 if ( i % 2 != 0 )6 sum += i;78 i++;9 }

1011 System.out.printf( "The sum is: %d\n", sum );

1 int product = 1, i = 0;23 while ( i <= 10 )4 {5 if ( i % 2 != 0 )6 i *= product;78 product++;9 }

1011 System.out.printf( "The product is: %d\n", product );

1 int product = 1, i = 0;23 while ( i <= 10 )4 {5 if ( i % 2 != 0 )6789 }

1011 System.out.printf( "The product is: %d\n", product );

<=

product *= i;

i++;

Chapter 4 Control Statements: Part 1 119

Lab Exercises

Name: Date:

Section:

Lab Exercise 1 — Credit

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. Description of the Problem

3. Sample Output

4. Program Template (Fig. L 4.1 and Fig. L 4.2)

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 sample output, then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for 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 4 of Java How to Program: Seventh Edi-tion. In this lab, you will practice:

• Writing pseudocode.

• Using selection statements.

The follow-up questions and activities also will give you practice:

• Using counter-controlled repetition.

Description of the ProblemDevelop a Java application that will determine whether any of several department-store customers has exceededthe credit limit on a charge account. For each customer, the following facts are available:

a) account number

b) balance at the beginning of the month

c) total of all items charged by the customer this month

d) total of all credits applied to the customer’s account this month

e) allowed credit limit.

The program should input all of these facts as integers, calculate the new balance (= beginning balance + charges– credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit.For those customers whose credit limit is exceeded, the program should display the message "Credit limit

exceeded".

Lab Exercises Name:

Lab Exercise 1 — Credit

120 Control Statements: Part 1 Chapter4

Sample Output

Program Template

Enter Account Number (or -1 to quit): 1Enter Balance: 100Enter Charges: 80Enter Credits: 25Enter Credit Limit: 200New balance is 155

Enter Account Number (or -1 to quit): 2Enter Balance: 450Enter Charges: 240Enter Credits: 300Enter Credit Limit: vNew balance is 390

Enter Account Number (or -1 to quit): 3Enter Balance: 500Enter Charges: 300Enter Credits: 125Enter Credit Limit: 400New balance is 675Credit limit exceeded

Enter Account Number (or -1 to quit): -1

1 // Lab 1: Credit.java2 // Program monitors accounts.3 import java.util.Scanner;45 public class Credit6 {7 // calculates the balance on several credit accounts8 public void calculateBalance()9 {

10 Scanner input = new Scanner( System.in );1112 int account; // account number13 int oldBalance; // starting balance14 int charges; // total charges15 int credits; // total credits16 int creditLimit; // allowed credit limit17 int newBalance; // new balance1819 System.out.print( "Enter Account Number (or -1 to quit): " );20 /* write code to input an integer and store it in account */2122 /* write code to loop while the account number is not -1 */2324 /* write code to input the rest of the customer information. */2526 /* write code to compute the new balance */27

Fig. L 4.1 | Credit.java. (Part 1 of 2.)

Lab Exercises Name:

Lab Exercise 1 — Credit

Chapter 4 Control Statements: Part 1 121

Problem-Solving Tips1. There are five input values required. But the account number must be input before the loop in order totest whether it is equal to the sentinel value. So there should be six input statements, five in the loopand one before it.

2. Use the formula given in the problem description to compute the new balance.

3. Use an if statement to determine whether newBalance is larger than the customer’s creditLimit. If so,indicate that the credit limit was exceeded.

4. Write out your algorithms in pseudocode before writing any code.

5. Be sure to follow the spacing and indentation conventions mentioned in the text.

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

SolutionTop:

Determine if each of an arbitrary number of department store customers has exceeded the credit limit on acharge account.

First refinement:

Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, cal-culate the customer’s new balance and determine if the balance exceeds the credit limit. Then process the nextcustomer.

28 /* write code that will check if the new balance is greater than the29 credit limit and output the proper information */3031 /* write code to input a new account number and close the while loop. */3233 } // end method calculateBalance34 } // end class Credit

1 // Lab 1: CreditTest.java2 // Test application for class Credit3 public class CreditTest4 {5 public static void main(String args[])6 {7 Credit application = new Credit();8 application.calculateBalance();9 } // end main

10 } // end class CreditTest

Fig. L 4.2 | CreditTest.java

Fig. L 4.1 | Credit.java. (Part 2 of 2.)

Lab Exercises Name:

Lab Exercise 1 — Credit

122 Control Statements: Part 1 Chapter4

Second refinement:

Input the first customer’s account number

While the sentinel value (-1) has not been entered for the account numberInput the customer’s beginning balanceInput the customer’s total chargesInput the customer’s total creditsInput the customer’s credit limitCalculate the customer’s new balancePrint the new balance

If the balance exceeds the credit limitPrint "Credit Limit Exceeded"

Input the next customer’s account number

1 // Lab 1: Credit.java2 // Program monitors accounts.3 import java.util.Scanner;45 public class Credit6 {7 // calculates the balance on several credit accounts8 public void calculateBalance()9 {

10 Scanner input = new Scanner( System.in );1112 int account; // account number13 int oldBalance; // starting balance14 int charges; // total charges15 int credits; // total credits16 int creditLimit; // allowed credit limit17 int newBalance; // new balance1819 System.out.print( "Enter Account Number (or -1 to quit): " );20 account = input.nextInt(); // read in account number2122 // exit if the input is -1 otherwise, proceed with the program23 while ( account != -1 )24 {25 System.out.print( "Enter Balance: " );26 oldBalance = input.nextInt(); // read in original balance2728 System.out.print( "Enter Charges: " );29 charges = input.nextInt(); // read in charges3031 System.out.print( "Enter Credits: " );32 credits = input.nextInt(); // read in credits3334 System.out.print( "Enter Credit Limit: " );35 creditLimit = input.nextInt(); // read in credit limit3637 // calculate and display new balance38 newBalance = oldBalance + charges - credits;39 System.out.printf( "New balance is %d\n", newBalance );

Lab Exercises Name:

Lab Exercise 1 — Credit

Chapter 4 Control Statements: Part 1 123

Follow-Up Questions and Activities1. Modify the program to use counter-controlled repetition to process 10 accounts.

Solution

4041 // display a warning if the user has exceed the credit limit42 if ( newBalance > creditLimit )43 System.out.println( "Credit limit exceeded" );4445 System.out.print( "\nEnter Account Number (or -1 to quit): " );46 account = input.nextInt(); // read in next account number47 } // end while48 } // end method calculateBalance49 } // end class Credit

1 // Lab 1: CreditTest.java2 // Test application for class Credit3 public class CreditTest4 {5 public static void main(String args[])6 {7 Credit application = new Credit();8 application.calculateBalance();9 } // end main

10 } // end class CreditTest

1 // Lab 1: Credit.java2 // Program monitors accounts.3 import java.util.Scanner;45 public class Credit6 {7 // calculates the balance on several credit accounts8 public void calculateBalance()9 {

10 Scanner input = new Scanner( System.in );1112 int account; // account number13 int oldBalance; // starting balance14 int charges; // total charges15 int credits; // total credits16 int creditLimit; // allowed credit limit17 int newBalance; // new balance18 int count = 0; // number of accounts entered1920 // exit if the input is -1 otherwise, proceed with the program21 while ( count < 10 )22 {23 System.out.print( "\nEnter Account Number: " );24 account = input.nextInt(); // read in account number2526 System.out.print( "Enter Balance: " );27 oldBalance = input.nextInt(); // read in original balance

Lab Exercises Name:

Lab Exercise 1 — Credit

124 Control Statements: Part 1 Chapter4

2829 System.out.print( "Enter Charges: " );30 charges = input.nextInt(); // read in charges3132 System.out.print( "Enter Credits: " );33 credits = input.nextInt(); // read in credits3435 System.out.print( "Enter Credit Limit: " );36 creditLimit = input.nextInt(); // read in credit limit3738 // calculate and display new balance39 newBalance = oldBalance + charges - credits;40 System.out.printf( "New balance is %d\n", newBalance );4142 // display a warning if the user has exceed the credit limit43 if ( newBalance > creditLimit )44 System.out.println( "Credit limit exceeded" );4546 count++; // increment number of accounts input47 } // end while48 } // end method calculateBalance49 } // end class Credit

1 // Lab 1: CreditTest.java2 // Test application for class Credit3 public class CreditTest4 {5 public static void main(String args[])6 {7 Credit application = new Credit();8 application.calculateBalance();9 } // end main

10 } // end class CreditTest

Lab Exercises Name:

Lab Exercise 1 — Credit

Chapter 4 Control Statements: Part 1 125

Enter Account Number: 1Enter Balance: 100Enter Charges: 80Enter Credits: 25Enter Credit Limit: 200New balance is 155

Enter Account Number: 2Enter Balance: 450Enter Charges: 240Enter Credits: 300Enter Credit Limit: 600New balance is 390

Enter Account Number: 3Enter Balance: 500Enter Charges: 300Enter Credits: 125Enter Credit Limit: 400New balance is 675Credit limit exceeded

Enter Account Number: 4Enter Balance: 0Enter Charges: 350Enter Credits: 0Enter Credit Limit: 375New balance is 350

Enter Account Number: 5Enter Balance: 200Enter Charges: 300Enter Credits: 200Enter Credit Limit: 250New balance is 300Credit limit exceeded

Enter Account Number: 8Enter Balance: 250Enter Charges: 50Enter Credits: 200Enter Credit Limit: 250New balance is 100

Enter Account Number: 9Enter Balance: 500Enter Charges: 100Enter Credits: 300Enter Credit Limit: 300New balance is 300

Lab Exercises Name:

Lab Exercise 1 — Credit

126 Control Statements: Part 1 Chapter4

2. Modify the program to use counter-controlled repetition to process the number of accounts specified by theuser. The number of accounts should be input before processing any account information.

Solution

Enter Account Number: 10Enter Balance: 75Enter Charges: 240Enter Credits: 125Enter Credit Limit: 200New balance is 190

1 // Lab 1: Credit.java2 // Program monitors accounts.3 import java.util.Scanner;45 public class Credit6 {7 // calculates the balance on several credit accounts8 public void calculateBalance()9 {

10 Scanner input = new Scanner( System.in );1112 int account; // account number13 int oldBalance; // starting balance14 int charges; // total charges15 int credits; // total credits16 int creditLimit; // allowed credit limit17 int newBalance; // new balance18 int count = 0; // number of accounts entered19 int number; // number of accounts for user to enter2021 System.out.print( "Enter Number of Accounts: " );22 account = input.nextInt(); // read in number of accounts2324 // exit if the input is -1 otherwise, proceed with the program25 while ( count < number )26 {27 System.out.print( "Enter Account Number: " );28 account = input.nextInt(); // read in account number29

30 System.out.print( "Enter Balance: " );31 oldBalance = input.nextInt(); // read in original balance3233 System.out.print( "Enter Charges: " );34 charges = input.nextInt(); // read in charges3536 System.out.print( "Enter Credits: " );37 credits = input.nextInt(); // read in credits3839 System.out.print( "Enter Credit Limit: " );40 creditLimit = input.nextInt(); // read in credit limit4142 // calculate and display new balance

Lab Exercises Name:

Lab Exercise 1 — Credit

Chapter 4 Control Statements: Part 1 127

43 newBalance = oldBalance + charges - credits;44 System.out.printf( "New balance is %d\n", newBalance );4546 // display a warning if the user has exceed the credit limit47 if ( newBalance > creditLimit )48 System.out.println( "Credit limit exceeded" );4950 count++; // increment number of accounts input51 } // end while52 } // end method calculateBalance53 } // end class Credit

1 // Lab 1: CreditTest.java2 // Test application for class Credit3 public class CreditTest4 {5 public static void main(String args[])6 {7 Credit application = new Credit();8 application.calculateBalance();9 } // end main

10 } // end class CreditTest

Enter Number of Accounts: 3

Enter Account Number: 1Enter Balance: 100Enter Charges: 80Enter Credits: 25Enter Credit Limit: 200New balance is 155

Enter Account Number: 2Enter Balance: 450Enter Charges: 240Enter Credits: 300Enter Credit Limit: 600New balance is 390

Enter Account Number: 3Enter Balance: 500Enter Charges: 300Enter Credits: 125Enter Credit Limit: 400New balance is 675Credit limit exceeded

Lab Exercises Name:

Lab Exercise 1 — Credit

128 Control Statements: Part 1 Chapter4

Lab Exercises Name:

Lab Exercise 2 — Palindromes

Chapter 4 Control Statements: Part 1 129

Name: Date:

Section:

Lab Exercise 2 — Palindromes

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. Description of the Problem

3. Sample Output

4. Program Template (Fig. L 4.3 and Fig. L 4.4)

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 sample output, then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for 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 4 of Java How to Program: Seventh Edi-tion. In this lab you will practice:

• Using selection statements.

• Using sentinel-controlled repetition.

• Using if…else selection statements.

The follow-up question and activity will also give you practice:

• Modifying existing code to perform a similar task.

Description of the ProblemA palindrome is a sequence of characters that reads the same backward as forward. For example, each of the fol-lowing five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write an application that reads ina five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display anerror message and allow the user to enter a new value.

Sample Output

Enter a 5-digit number: 1234Number must be 5 digitsEnter a 5-digit number: 123456Number must be 5 digitsEnter a 5-digit number: 5434554345 is a palindrome!!!

Lab Exercises Name:

Lab Exercise 2 — Palindromes

130 Control Statements: Part 1 Chapter4

Program Template

1 // Lab 2: Palindrome.java2 // Program tests for a palindrome3 import java.util.Scanner;45 public class Palindrome6 {7 // checks if a 5-digit number is a palindrome8 public void checkPalindrome()9 {

10 Scanner input = new Scanner( System.in );1112 int number; // user input number13 int digit1; // first digit14 int digit2; // second digit15 int digit4; // fourth digit16 int digit5; // fifth digit17 int digits; // number of digits in input1819 number = 0;20 digits = 0;2122 /* Write code that inputs a five-digit number. Display an error message23 if the number is not five digits. Loop until a valid input is received. */2425 /* Write code that separates the digits in the five digit number. Use26 division to isolate the left-most digit in the number, use a remainder27 calculation to remove that digit from the number. Then repeat this28 process. */2930 /* Write code that determines whether the first and last digits are31 identical and the second and Fourth digits are identical. Output32 whether or not the original string is a palindrome. */3334 } // end method checkPalindrome35 } // end class Palindrome

Fig. L 4.3 | Palindrome.java.

1 // Lab 2: PalindromeTest.java2 // Test application for class Palindrome3 public class PalindromeTest4 {5 public static void main( String args[] )6 {7 Palindrome application = new Palindrome();8 application.checkPalindrome();9 } // end main

10 } // end class PalindromeTest

Fig. L 4.4 | PalindromeTest.java

Lab Exercises Name:

Lab Exercise 2 — Palindromes

Chapter 4 Control Statements: Part 1 131

Solution

1 // Lab 2: Palindrome.java2 // Program tests for a palindrome3 import java.util.Scanner;45 public class Palindrome6 {7 // checks if a 5-digit number is a palindrome8 public void checkPalindrome()9 {

10 Scanner input = new Scanner( System.in );1112 int number; // user input number13 int digit1; // first digit14 int digit2; // second digit15 int digit4; // fourth digit16 int digit5; // fifth digit17 int digits; // number of digits in input1819 number = 0;20 digits = 0;2122 // Ask for a number until it is five digits23 while ( digits != 5 )24 {25 System.out.print( "Enter a 5-digit number: " );26 number = input.nextInt();2728 if ( number < 100000 )29 {30 if ( number > 9999 )31 digits = 5;32 else33 System.out.println( "Number must be 5 digits" );34 } // end if35 else36 System.out.println( "Number must be 5 digits" );37 } // end while loop3839 // get the digits40 digit1 = number / 10000;41 digit2 = number % 10000 / 1000;42 digit4 = number % 10000 % 1000 % 100 / 10;43 digit5 = number % 10000 % 1000 % 100 % 10;4445 // print whether the number is a palindrome46 System.out.print( number );4748 if ( digit1 == digit5 )49 {50 if ( digit2 == digit4 )51 System.out.println( " is a palindrome!!!" );52 else53 System.out.println( " is not a palindrome." );54 }

Lab Exercises Name:

Lab Exercise 2 — Palindromes

132 Control Statements: Part 1 Chapter4

Problem-Solving Tips1. Determine the number of digits in the value input by the user and assign the result to digits. Use a

while loop to determine whether the user input contains the proper number of digits. In the condition,determine whether digits is equal to five. If not, input a new value from the user and determine wheth-er the new value contains the proper number of digits. When the number of digits is five, the loopshould terminate.

2. Use division and remainder calculations to obtain the separate digits. For a five-digit number to be apalindrome, the first and fifth digits must be the same and the second and fourth digits must be thesame.

3. Be sure to follow the spacing and indentation conventions mentioned in the text.

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

Follow-Up Question and Activity1. Modify the program to determine whether a seven-digit number is a palindrome.

Solution

55 else56 System.out.println( " is not a palindrome." );57 } // end method checkPalindrome58 } // end class Palindrome

1 // Lab 2: PalindromeTest.java2 // Test application for class Palindrome3 public class PalindromeTest4 {5 public static void main( String args[] )6 {7 Palindrome application = new Palindrome();8 application.checkPalindrome();9 } // end main

10 } // end class PalindromeTest

1 // Lab 2: Palindrome.java2 // Program tests for a palindrome3 import java.util.Scanner;45 public class Palindrome6 {7 // checks if a 5-digit number is a palindrome8 public void checkPalindrome()9 {

10 Scanner input = new Scanner( System.in );1112 int number; // user input number13 int digit1; // first digit14 int digit2; // second digit15 int digit3; // third digit16 int digit5; // fifth digit17 int digit6; // sixth digit

Lab Exercises Name:

Lab Exercise 2 — Palindromes

Chapter 4 Control Statements: Part 1 133

18 int digit7; // seventh digit19 int digits; // number of digits in input2021 number = 0;22 digits = 0;2324 // Ask for a number until it is seven digits25 while ( digits != 7 )26 {27 System.out.print( "Enter a 7-digit number: " );28 number = input.nextInt();2930 if ( number < 10000000 )31 {32 if ( number > 999999 )33 digits = 7;34 else35 System.out.println( "Number must be 7 digits" );36 } // end if37 else38 System.out.println( "Number must be 7 digits" );39 } // end while loop4041 // get the digits42 digit1 = number / 1000000;43 digit2 = number % 1000000 / 100000;44 digit3 = number % 100000 / 10000;45 digit5 = number % 1000 / 100;46 digit6 = number % 100 / 10;47 digit7 = number % 10;4849 // print whether the number is a palindrome50 System.out.print( number );5152 if ( digit1 == digit7 )53 {54 if ( digit2 == digit6 )55 {56 if ( digit3 == digit5 )57 System.out.println( " is a palindrome!!!" );58 else59 System.out.println( " is not a palindrome." );60 }61 else62 System.out.println( " is not a palindrome." );63 }64 else65 System.out.println( " is not a palindrome." );66 } // end method checkPalindrome67 } // end class Palindrome

1 // Lab 2: PalindromeTest.java2 // Test application for class Palindrome3 public class PalindromeTest4 {5 public static void main( String args[] )6 {

Lab Exercises Name:

Lab Exercise 2 — Palindromes

134 Control Statements: Part 1 Chapter4

7 Palindrome application = new Palindrome();8 application.checkPalindrome();9 } // end main

10 } // end class PalindromeTest

Enter a 7-digit number: 76545677654567 is a palindrome!!!

Enter a 7-digit number: 76543217654321 is not a palindrome.

Lab Exercises Name:

Lab Exercise 3 — Largest Number

Chapter 4 Control Statements: Part 1 135

Name: Date:

Section:

Lab Exercise 3 — Largest Number

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. Description of the Problem

3. Sample Output

4. Program Template (Fig. L 4.5 and Fig. L 4.6)

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 sample output, then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for 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 4 of Java How to Program: Seventh Edi-tion. In this lab you will practice:

• Using while statements

• Using counter-controlled repetition

• Using if statements

The follow-up question and activity also will give you practice:

• Using if…else statements.

Description of the ProblemThe process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computerapplications. For example, a program that determines the winner of a sales contest would input the number ofunits sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocodeprogram and then a Java application that inputs a series of 10 integers and determines and prints the largest in-teger. Your program should use at least the following three variables:

a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and todetermine when all 10 numbers have been processed).

b) number: The integer most recently input by the user.

c) largest: The largest number found so far.

Lab Exercises Name:

Lab Exercise 3 — Largest Number

136 Control Statements: Part 1 Chapter4

Sample Output

Program Template

Enter number: 56Enter number: -10Enter number: 200Enter number: 25Enter number: 8Enter number: 500Enter number: -20Enter number: 678Enter number: 345Enter number: 45Largest number is 678

1 // Lab 3: Largest.java2 // Program determines and prints the largest of ten numbers.3 import java.util.Scanner;45 public class Largest6 {7 // determine the largest of 10 numbers8 public void determineLargest()9 {

10 Scanner input = new Scanner( System.in );1112 int largest; // largest number13 int number; // user input14 int counter; // number of values entered1516 /* write code to get the first integer and store it in variable largest */1718 /* write code to initialize the number of integers entered */1920 /* write code to loop until 10 numbers are entered */2122 /* write code to prompt the user to enter a number and read tat number */2324 /* write code to test whether the number entered is greater than the largest25 if so, replace the value of largest with the entered number */2627 /* write code to increment the number of integers entered */2829 System.out.printf( "Largest number is %d\n", largest );30 } // end method determineLargest31 } // end class Largest

Fig. L 4.5 | Largest.java

Lab Exercises Name:

Lab Exercise 3 — Largest Number

Chapter 4 Control Statements: Part 1 137

Problem-Solving Tips1. Remember to initialize the count of the number of integers entered.

2. Use an if statement to test whether the number input from the user is larger than the largest numberyou have stored.

3. Be sure to follow the spacing and indentation conventions mentioned in the text.

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

Solution

1 // Lab 3: LargestTest.java2 // Test application for class Largest3 public class LargestTest4 {5 public static void main( String args[] )6 {7 Largest application = new Largest();8 application.determineLargest();9 } // end main

10 } // end class LargestTest

Fig. L 4.6 | LargestTest.java

1 // Lab 3: Largest.java2 // Program determines and prints the largest of ten numbers.3 import java.util.Scanner;45 public class Largest6 {7 // determine the largest of 10 numbers8 public void determineLargest()9 {

10 Scanner input = new Scanner( System.in );1112 int largest; // largest number13 int number; // user input14 int counter; // number of values entered1516 // get first number and assign it to variable largest17 System.out.print( "Enter number: " );18 largest = input.nextInt();1920 counter = 1;2122 // get rest of the numbers and find the largest23 while ( counter < 10 )24 {25 System.out.print( "Enter number: " );26 number = input.nextInt();2728 if ( number > largest )29 largest = number;3031 counter++;32 } // end while loop

Lab Exercises Name:

Lab Exercise 3 — Largest Number

138 Control Statements: Part 1 Chapter4

Follow-Up Question and Activity1. Modify the program to find the two largest values of the 10 values entered.

Solution

3334 System.out.printf( "Largest number is %d\n", largest );35 } // end method determineLargest36 } // end class Largest

1 // Lab 3: LargestTest.java2 // Test application for class Largest3 public class LargestTest4 {5 public static void main( String args[] )6 {7 Largest application = new Largest();8 application.determineLargest();9 } // end main

10 } // end class LargestTest

1 // Lab 3: TwoLargest.java2 // Program determines and prints the two largest of ten numbers.3 import java.util.Scanner;45 public class TwoLargest6 {7 // determine the two largest of 10 integers8 public void determineTwoLargest()9 {

10 Scanner input = new Scanner( System.in );1112 int largest; // largest number13 int nextLargest; // second largest number14 int number; // user input15 int counter; // number of values entered1617 // get first number and assign it to variable largest18 System.out.print( "Enter number: " );19 largest = input.nextInt();2021 // get second number and compare it with first number22 System.out.print( "Enter number: " );23 number = input.nextInt();2425 if ( number > largest )26 {27 nextLargest = largest;28 largest = number;29 } // end if30 else31 nextLargest = number;32

Lab Exercises Name:

Lab Exercise 3 — Largest Number

Chapter 4 Control Statements: Part 1 139

33 counter = 2;3435 // get rest of the numbers and find the largest and nextLargest36 while ( counter < 10 )37 {38 System.out.print( "Enter number: " );39 number = input.nextInt();4041 if ( number > largest ) {42 nextLargest = largest;43 largest = number;44 } // end if45 else if ( number > nextLargest )46 nextLargest = number;4748 counter++;49 } // end while loop5051 System.out.printf( "Largest number is %d\nSecond largest number is %d\n",52 largest, nextLargest );53 } // end method determineTwoLargest54 } // end class TwoLargest

1 // Lab 3: TwoLargestTest.java2 // Test application for class TwoLargest3 public class TwoLargestTest4 {5 public static void main( String args[] )6 {7 TwoLargest application = new TwoLargest();8 application.determineTwoLargest();9 } // end main

10 } // end class TwoLargestTest

Enter number: 56Enter number: -10Enter number: 200Enter number: 25Enter number: 8Enter number: 500Enter number: -20Enter number: 678Enter number: 345Enter number: 45Largest number is 678

Lab Exercises Name:

Debugging

Chapter 4 Control Statements: Part 1 141

Name: Date:

Section:

Debugging

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 logicerrors that exist. The sample output demonstrates what the program’s output should be once the program’s codeis corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel.

Sample Output

Broken Code

1 for Fahrenheit to Celsius2 for Celsius to Fahrenheit3 to quit:1Enter the degrees in Fahrenheit:212The temp in Celsius is 1001 for Fahrenheit to Celsius2 for Celsius to Fahrenheit3 to quit:2Enter the degrees in Celsius:100The temp in Fahrenheit is 2121 for Fahrenheit to Celsius2 for Celsius to Fahrenheit3 to quit:3

1 // Chapter 4 of Java How To Program2 // Debugging Problem3 import java.util.Scanner;45 public class Temperature6 {7 public static void main( String args[] )8 {9 int option;

10 int degree1;11 int celsius1;12 int fahrenheit1;1314 Scanner input = new Scanner( System.in );1516 option = 0;17

Fig. L 4.7 | Temperature.java. (Part 1 of 2.)

Lab Exercises Name:

Debugging

142 Control Statements: Part 1 Chapter4

Solution

18 While ( option != 3 )1920 System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius",21 "2 for Celsius to Fahrenheit", "3 to quit:" );22 option = input.nextDouble();2324 System.out.println( "Enter the degrees in Fahrenheit: " );25 degree1 = input.nextDouble();2627 celsius1 = ( degree1 - 32 ) * 5 / 9;28 System.out.printf( "The temp in Celsius is %d\n", celsius1 );2930 if ( option == 2 );3132 System.out.println( "Enter the degrees in Celsius: " );33 degree1 = input.nextDouble();3435 fahrenheit1 = ( degree1 * 9 / 5 ) + 32;36 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 );37 } // end while loop38 } // end method Main39 } // end class Temperature

1 // Chapter 4 of Java How To Program2 // Debugging Problem3 import java.util.Scanner;45 public class Temperature6 {7 public static void main( String args[] )8 {9 int option;

10 int degree1;11 int celsius1;12 int fahrenheit1;1314 Scanner input = new Scanner( System.in );1516 option = 0;1718 ( option != 3 )1920 System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius",21 "2 for Celsius to Fahrenheit", "3 to quit:" );22 option = input. ;23242526 System.out.println( "Enter the degrees in Fahrenheit: " );27 degree1 = input. ;2829 celsius1 = ( degree1 - 32 ) * 5 / 9;30 System.out.printf( "The temp in Celsius is %d\n", celsius1 );31

Fig. L 4.7 | Temperature.java. (Part 2 of 2.)

while{

nextInt()

if ( option == 1 ){

nextInt()

}

Lab Exercises Name:

Debugging

Chapter 4 Control Statements: Part 1 143

List of Errors• Keyword while is spelled with a an uppercase “W” on line 18, which is compilation error.

• The while statement is missing an opening brace on line 19.

• An if…else statement testing for option equal to 1 is omitted. It has been added to line 24 and theelse part has been added to the beginning of line 30.

• Opening (lines 23 and 31) and closing (lines 29 and 37) braces are left out in the if…else statementwhich leads to either a compilation or logic error.

• The if statement (line 30) has a semicolon after the condition which leads to a logic error.

• The program should use Scanner method nextInt instead of method nextDouble on lines 25 and 33to input an integer from the user.

32 if ( option == 2 )3334 System.out.println( "Enter the degrees in Celsius: " );35 degree1 = input. ;3637 fahrenheit1 = ( degree1 * 9 / 5 ) + 32;38 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 );3940 } // end while loop41 } // end method Main42 } // end class Temperature

else{

nextInt()

}

Chapter 4 Control Statements: Part 1 145

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 Java application that inputs an integer and uses an if statement to determine whether the integer iseven and, if it is, prints that number.

2. Write a Java application that inputs an integer and uses an if…else statement to determine whether theinteger is odd or even. If it is odd, print the number followed by "is odd"; if it is even, print the numberfollowed by "is even".

1 public class Test22 {3 public static void main( String args[] )4 {5 Scanner input = new Scanner( System.in );6 int number1;78 System.out.print( "Enter an integer: " );9 number1 = input.nextInt();

1011 if ( number1 % 2 == 0 )12 System.out.println( number1 );13 } // end main14 } // end class Test2

Enter an integer: 88

1 public class Test22 {3 public static void main( String args[] )4 {5 Scanner input = new Scanner( System.in );6 int number1;78 System.out.print( "Enter an integer: " );9 number1 = input.nextInt();

1011 if ( number1 % 2 == 0 )12 System.out.printf( "%d is even\n", number1 );13 else14 System.out.printf( "%d is odd\n", number1 );15 } // end main16 } // end class Test2

Postlab Activities Name:

Coding Exercises

146 Control Statements: Part 1 Chapter4

3. Rewrite your solution to Coding Exercise 2 so that it uses the conditional operator (?:), rather than anif…else statement.

4. Write a Java application that uses a counter-controlled loop to sum the integers in the range 1–10, then com-pute the average of those numbers (as an integer value). Display the sum and the average.

Enter an integer: 77 is odd

1 public class Test22 {3 public static void main( String args[] )4 {5 Scanner input = new Scanner( System.in );6 int number1;78 System.out.print( "Enter an integer: " );9 number1 = input.nextInt();

1011 System.out.printf( "%d is %s\n", number1,12 ( ( number1 % 2 == 0 ) ? "even" : "odd" ) );13 } // end main14 } // end class Test2

Enter an integer: 77 is odd

1 public class Test22 {3 // main method begins execution of Java application4 public static void main( String args[] )5 {6 int count = 0;7 int numbers = 1;89 while ( numbers < 11 )

10 {11 count += numbers;12 numbers++;13 }1415 System.out.printf( "The sum of the first ten integers is %d\n", count );16 System.out.printf( "The average of the first ten integers is %d\n", count / 10 );17 } // end method main18 } // end class average

The sum of the first ten integers is 55The average of the first ten integers is 5

Postlab Activities Name:

Coding Exercises

Chapter 4 Control Statements: Part 1 147

5. Modify your solution to Coding Exercise 4 so that a user can specify the range of numbers to average.

6. Write a Java application that uses a loop to read in 10 numbers and calculates and prints their sum.

1 import java.util.Scanner;23 public class Test24 {5 // main method begins execution of Java application6 public static void main( String args[] )7 {8 Scanner input = new Scanner( System.in );9 int count = 0;

10 int numbers;11 int max;12 int range;1314 System.out.print( "Please enter the low end of the range of numbers: " );15 numbers = input.nextInt();1617 System.out.print( "Please enter the high end of the range of numbers: " );18 max = input.nextInt();19 range = max - numbers;2021 while ( numbers < max )22 {23 count += numbers;24 numbers++;25 }2627 System.out.printf( "The sum of the integers is %d\n", count );28 System.out.printf( "The average of the integers is %d\n", count / range );29 } // end method main30 } // end class average

Please enter the low end of the range of numbers: 5Please enter the high end of the range of numbers: 10The sum of the integers is 35The average of the integers is 7

1 import java.util.Scanner;23 public class Test24 {5 // main method begins execution of Java application6 public static void main( String args[] )7 {8 Scanner input = new Scanner( System.in );9 int counter = 0;

10 int number = 1;11 int sum = 0;1213 System.out.println( "Please enter ten integers" );

Postlab Activities Name:

Coding Exercises

148 Control Statements: Part 1 Chapter4

1415 while ( counter < 10 )16 {17 number = input.nextInt();18 sum += number;19 counter++;20 }2122 System.out.printf( "The sum of the first ten integers is %d\n", sum );23 System.out.printf( "The average of the first ten integers is %d\n", sum / 10 );24 } // end method main25 } // end class average

Please enter ten integers2468101214161820The sum of the first ten integers is 110The average of the first ten integers is 11