0% found this document useful (0 votes)
74 views40 pages

Control Statements: Part 1: Let's All Move One Place On

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

Control Statements: Part 1: Let's All Move One Place On

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

4

Control
Let’s all move one place on.
Statements: Part 1
—Lewis Carroll

The wheel is come full circle.


—William Shakespeare

How many apples fell on


Newton’s head before he took OBJECTIVES
the hint!
—Robert Frost In this chapter you will learn:
■ To use basic problem-solving techniques.
All the evolution we know of
proceeds from the vague to ■ To develop algorithms through the process of top-down,
the definite. stepwise refinement.
—Charles Sanders Peirce
■ To use the if and if…else 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.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 77

Assignment Checklist
Name: Date:

Section:

Exercises Assigned: Circle assignments Date Due

Prelab Activities
Matching YES NO
Fill in the Blank 18, 19, 20, 21, 22, 23, 24, 25, 26,
27
Short Answer 28, 29, 30, 31, 32, 33, 34, 35, 36
Programming Output 37, 38, 39, 40, 41, 42, 43, 44, 45,
46
Correct the Code 47, 48, 49, 50, 51, 52, 53, 54
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
Labs Provided by Instructor
1.
2.
3.
Postlab Activities
Coding Exercises 1, 2, 3, 4, 5, 6
Programming Challenges 1, 2

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 79

Prelab Activities
Matching

Name: Date:

Section:

After reading Chapter 4 of Java How to Program: Seventh Edition, answer the given questions. These questions
are intended to test and reinforce your understanding of key Java concepts. You may answer these questions ei-
ther before or during the lab.

For each term in the left column, write the letter for the description that best matches the term from the right
column.

Term Description

1. -- a) Java’s only ternary operator.


2. ++ b) A selection statement that executes an indicated action
3. ?:
only when the condition is true.
4. algorithm c) An artificial and informal language that helps program-
mers develop algorithms.
5. selection statement
d) A process for refining pseudocode by maintaining a
6. sentinel-controlled repetition complete program representation for each refinement.
7. ; e) Allows the programmer to specify that an action is to be
8. pseudocode repeated while some condition remains true.
9. repetition statement f) A selection statement that specifies separate actions to
execute when a condition is true and when a condition
10. counter-controlled repetition is false.
11. program control g) Specifying the order in which statements are to be exe-
12. top-down, stepwise refinement cuted in a computer program.
13. if h) Chooses among alternative courses of action in a pro-
gram.
14. if…else
i) Increment operator.
15. block
j) A set of statements contained within a pair of braces.
16. +=, -=, *=, /=, %=
k) A procedure for solving a problem in terms of the ac-
17. primitive types tions to execute and the order in which the actions
should 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 before
the loop begins executing.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 81

Prelab Activities Name:

Fill in the Blank

Fill in the Blank

Name: Date:

Section:

Fill in the blanks for each of the following statements:

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

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

20. is a process for refining pseudocode by maintaining a complete representation 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 referred
to as a(n) language.

22. Java uses internationally recognized standards for both and numbers.

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

24. The selection statement specifies separate actions to execute when the condition is true and when
the condition is false.

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

26. Unary cast operator creates a temporary double-precision, floating-point copy of its operand.

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 83

Prelab Activities Name:

Short Answer

Short Answer

Name: Date:

Section:

Answer the following questions in the space provided. Your answers should be concise; aim for two or three sen-
tences.

28. Explain the purpose of a selection statement.

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

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
84 Control Statements: Part 1 Chapter4

Prelab Activities Name:

Short Answer

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

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

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 85

Prelab Activities Name:

Short Answer

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

35. Explain how repetition statements are used.

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 87

Prelab Activities Name:

Programming Output

Programming Output

Name: Date:

Section:

For each of the given program segments, read the code and write the output in the space provided below each
program. [Note: Do not execute these programs on a computer.]

For questions 37–39 assume the following class definition:

1 public class Test2


2 {
3 public static void main( String args[] )
4 {
5 Scanner input = new Scanner();
6 int number1;
7
8 System.out.println( "Enter an integer:" );
9 number1 = input.nextInt();
10
11 if ( number1 % 2 == 0 )
12 System.out.println( "%d is even\n", number1 );
13 else
14 System.out.println( "%d is odd\n", number1 );
15 } // end main
16 } // end class Test2

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:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
88 Control Statements: Part 1 Chapter4

Prelab Activities Name:

Programming Output

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

1 number1 = number1 + 3;

Your answer:

40. What is output by the following program?

1 public class Grade


2 {
3 public static void main( String args[] )
4 {
5 int grade1 = 65;
6 int grade2 = 50;
7
8 System.out.println( grade1 >= 60 ? "Passed." : "Failed." );
9 System.out.println( grade2 >= 60 ? "Passed." : "Failed." );
10 } // end main
11 } // end class Grade

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 89

Prelab Activities Name:

Programming Output

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

1 public class Value


2 {
3 public static void main( String args[] )
4 {
5 int x;
6 int xLimit;
7
8 /* 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 while
15
16 System.out.printf( "The final value of x is %d\n", x );
17 } // end main
18 } // end class Value

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

1 x = 1;
2 xLimit = 5;

Your answer:

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

1 x = 1;
2 xLimit = -2;

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
90 Control Statements: Part 1 Chapter4

Prelab Activities Name:

Programming Output

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

1 x = 10;
2 xLimit = 5;

Your answer:

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

1 public class Value


2 {
3 public static void main( String args[] )
4 {
5 int x;
6 int xLimit;
7
8 /* assign values to x and xLimit here */
9
10 while ( x <= xLimit )
11 {
12 x++;
13
14 if ( x % 2 == 0 )
15 System.out.printf( "%d is even.\n", x );
16 else
17 System.out.printf( "%d is odd.\n", x );
18 } // end while
19 } // end main
20 } // end class Value

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

1 x = 0;
2 xLimit = 10;

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 91

Prelab Activities Name:

Programming Output

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

1 x = 0
2 xLimit = -2;

Your answer:

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

1 x = 10;
2 xLimit = 5;

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 93

Prelab Activities Name:

Correct the Code

Correct the Code

Name: Date:

Section:

Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a compilation error, circle the error in the program and write the corrected code in the space
provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more
than one error in each program segment.]

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

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

Your answer:

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

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

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
94 Control Statements: Part 1 Chapter4

Prelab Activities Name:

Correct the Code

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

1 int i = 0;
2
3 while ( i <= 20 )
4
5 if ( i % 2 = 0 )
6 System.out.printf( "%d ", i );
7
8 i++

Your answer:

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

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

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 95

Prelab Activities Name:

Correct the Code

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

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

Your answer:

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

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

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
96 Control Statements: Part 1 Chapter4

Prelab Activities Name:

Correct the Code

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

1 int sum = 0, i = 0;
2
3 while ( i < 15 )
4 {
5 if ( i % 2 != 0 )
6 sum += i;
7
8 i++;
9 }
10
11 System.out.printf( "The sum is: %d\n", sum );

Your answer:

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

1 int product = 1, i = 0;
2
3 while ( i <= 10 )
4 {
5 if ( i % 2 != 0 )
6 i *= product;
7
8 product++;
9 }
10
11 System.out.printf( "The product is: %d\n", product );

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 97

Lab Exercises
Lab Exercise 1 — Credit

Name: Date:

Section:

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. 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 replaced
with 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 the
program. Compare your output with the sample output provided. Then answer the follow-up questions. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 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 Problem


Develop a Java application that will determine whether any of several department-store customers has exceeded
the 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".

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
98 Control Statements: Part 1 Chapter4

Lab Exercises Name:

Lab Exercise 1 — Credit

Sample Output

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


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

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


Enter Balance: 450
Enter Charges: 240
Enter Credits: 300
Enter Credit Limit: v
New balance is 390

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


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

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

Program Template

1 // Lab 1: Credit.java
2 // Program monitors accounts.
3 import java.util.Scanner;
4
5 public class Credit
6 {
7 // calculates the balance on several credit accounts
8 public void calculateBalance()
9 {
10 Scanner input = new Scanner( System.in );
11
12 int account; // account number
13 int oldBalance; // starting balance
14 int charges; // total charges
15 int credits; // total credits
16 int creditLimit; // allowed credit limit
17 int newBalance; // new balance
18
19 System.out.print( "Enter Account Number (or -1 to quit): " );
20 /* write code to input an integer and store it in account */
21
22 /* write code to loop while the account number is not -1 */
23
24 /* write code to input the rest of the customer information. */
25
26 /* write code to compute the new balance */
27

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 99

Lab Exercises Name:

Lab Exercise 1 — Credit

28 /* write code that will check if the new balance is greater than the
29 credit limit and output the proper information */
30
31 /* write code to input a new account number and close the while loop. */
32
33 } // end method calculateBalance
34 } // end class Credit

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

1 // Lab 1: CreditTest.java
2 // Test application for class Credit
3 public class CreditTest
4 {
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

Problem-Solving Tips
1. There are five input values required. But the account number must be input before the loop in order to
test whether it is equal to the sentinel value. So there should be six input statements, five in the loop
and 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.

Follow-Up Questions and Activities


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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 101

Lab Exercises Name:

Lab Exercise 2 — Palindromes

Lab Exercise 2 — Palindromes

Name: Date:

Section:

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. 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 replaced
with 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 the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 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 Problem


A 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 in
a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an
error message and allow the user to enter a new value.

Sample Output

Enter a 5-digit number: 1234


Number must be 5 digits
Enter a 5-digit number: 123456
Number must be 5 digits
Enter a 5-digit number: 54345
54345 is a palindrome!!!

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
102 Control Statements: Part 1 Chapter4

Lab Exercises Name:

Lab Exercise 2 — Palindromes

Program Template

1 // Lab 2: Palindrome.java
2 // Program tests for a palindrome
3 import java.util.Scanner;
4
5 public class Palindrome
6 {
7 // checks if a 5-digit number is a palindrome
8 public void checkPalindrome()
9 {
10 Scanner input = new Scanner( System.in );
11
12 int number; // user input number
13 int digit1; // first digit
14 int digit2; // second digit
15 int digit4; // fourth digit
16 int digit5; // fifth digit
17 int digits; // number of digits in input
18
19 number = 0;
20 digits = 0;
21
22 /* Write code that inputs a five-digit number. Display an error message
23 if the number is not five digits. Loop until a valid input is received. */
24
25 /* Write code that separates the digits in the five digit number. Use
26 division to isolate the left-most digit in the number, use a remainder
27 calculation to remove that digit from the number. Then repeat this
28 process. */
29
30 /* Write code that determines whether the first and last digits are
31 identical and the second and Fourth digits are identical. Output
32 whether or not the original string is a palindrome. */
33
34 } // end method checkPalindrome
35 } // end class Palindrome

Fig. L 4.3 | Palindrome.java.

1 // Lab 2: PalindromeTest.java
2 // Test application for class Palindrome
3 public class PalindromeTest
4 {
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

Problem-Solving Tips
1. 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,

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 103

Lab Exercises Name:

Lab Exercise 2 — Palindromes

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 loop
should terminate.
2. Use division and remainder calculations to obtain the separate digits. For a five-digit number to be a
palindrome, the first and fifth digits must be the same and the second and fourth digits must be the
same.
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 Activity


1. Modify the program to determine whether a seven-digit number is a palindrome.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 105

Lab Exercises Name:

Lab Exercise 3 — Largest Number

Lab Exercise 3 — Largest Number

Name: Date:

Section:

The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. 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 replaced
with 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 the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 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 Problem


The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer
applications. For example, a program that determines the winner of a sales contest would input the number of
units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode
program 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 to
determine 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.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
106 Control Statements: Part 1 Chapter4

Lab Exercises Name:

Lab Exercise 3 — Largest Number

Sample Output

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

Program Template

1 // Lab 3: Largest.java
2 // Program determines and prints the largest of ten numbers.
3 import java.util.Scanner;
4
5 public class Largest
6 {
7 // determine the largest of 10 numbers
8 public void determineLargest()
9 {
10 Scanner input = new Scanner( System.in );
11
12 int largest; // largest number
13 int number; // user input
14 int counter; // number of values entered
15
16 /* write code to get the first integer and store it in variable largest */
17
18 /* write code to initialize the number of integers entered */
19
20 /* write code to loop until 10 numbers are entered */
21
22 /* write code to prompt the user to enter a number and read tat number */
23
24 /* write code to test whether the number entered is greater than the largest
25 if so, replace the value of largest with the entered number */
26
27 /* write code to increment the number of integers entered */
28
29 System.out.printf( "Largest number is %d\n", largest );
30 } // end method determineLargest
31 } // end class Largest

Fig. L 4.5 | Largest.java

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 107

Lab Exercises Name:

Lab Exercise 3 — Largest Number

1 // Lab 3: LargestTest.java
2 // Test application for class Largest
3 public class LargestTest
4 {
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

Problem-Solving Tips
1. 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 number
you 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.

Follow-Up Question and Activity


1. Modify the program to find the two largest values of the 10 values entered.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 109

Lab Exercises Name:

Debugging

Debugging

Name: Date:

Section:

The program in this section does not run properly. Fix all the compilation errors, so that the program will com-
pile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic
errors that exist. The sample output demonstrates what the program’s output should be once the program’s code
is corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel.

Sample Output

1 for Fahrenheit to Celsius


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

Broken Code

1 // Chapter 4 of Java How To Program


2 // Debugging Problem
3 import java.util.Scanner;
4
5 public class Temperature
6 {
7 public static void main( String args[] )
8 {
9 int option;
10 int degree1;
11 int celsius1;
12 int fahrenheit1;
13
14 Scanner input = new Scanner( System.in );
15
16 option = 0;
17

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
110 Control Statements: Part 1 Chapter4

Lab Exercises Name:

Debugging

18 While ( option != 3 )
19
20 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();
23
24 System.out.println( "Enter the degrees in Fahrenheit: " );
25 degree1 = input.nextDouble();
26
27 celsius1 = ( degree1 - 32 ) * 5 / 9;
28 System.out.printf( "The temp in Celsius is %d\n", celsius1 );
29
30 if ( option == 2 );
31
32 System.out.println( "Enter the degrees in Celsius: " );
33 degree1 = input.nextDouble();
34
35 fahrenheit1 = ( degree1 * 9 / 5 ) + 32;
36 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 );
37 } // end while loop
38 } // end method Main
39 } // end class Temperature

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 111

Postlab Activities
Coding Exercises

Name: Date:

Section:

These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.

For each of the following problems, write a program or a program segment that performs the specified action.
1. Write a Java application that inputs an integer and uses an if statement to determine whether the integer is
even 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 the
integer is odd or even. If it is odd, print the number followed by "is odd"; if it is even, print the number
followed by "is even".

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
112 Control Statements: Part 1 Chapter4

Postlab Activities Name:

Coding Exercises

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.

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.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 113

Postlab Activities Name:

Programming Challenges

Programming Challenges

Name: Date:

Section:

The Programming Challenges are more involved than the Coding Exercises and may require a significant amount
of time to complete. Write a Java program for each of the problems in this section. The answers to these problems
are available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Pseudocode, hints or sample
outputs are provided for each problem to aid you in your programming.

1. Write a Java application that uses looping to print the following table of values:

N 10*N 100*N 1000*N

1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000

Hints:
• Use the following line of code to print out the heading of the table:
System.out.println( "N\t10*N\t100*N\t1000*N\n" );

• You should use one more print statement inside a while loop to print the rest of the table.
2. Write an application that uses only the output statements
System.out.print( "* " );
System.out.print( " " );
System.out.println();

to display in the command window the checkerboard pattern that follows:

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

Hints:
• Note that println with no arguments outputs a newline.
• A nested repetition statement is required in this exercise.

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

You might also like