Control Statements: Part 1: Let's All Move One Place On
Control Statements: Part 1: Let's All Move One Place On
Control
Let’s all move one place on.
Statements: Part 1
—Lewis Carroll
© 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:
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
© 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
Name: Date:
Section:
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.
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
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.
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
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
Short Answer
34. Use pseudocode to give an example of a looping construct in which the number of repetitions is not known
in advance.
© 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
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.]
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
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:
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 89
Programming Output
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
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:
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
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
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
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
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
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.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
98 Control Statements: Part 1 Chapter4
Sample Output
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
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 99
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
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
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.
© 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
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.
Sample Output
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
102 Control Statements: Part 1 Chapter4
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
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
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
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.
© 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
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.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
106 Control Statements: Part 1 Chapter4
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
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4 Control Statements: Part 1 107
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
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.
© 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
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
Broken Code
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
110 Control Statements: Part 1 Chapter4
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
© 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
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
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:
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();
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
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.