Exercises


[Page 298]

Note

For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.


Exercise 6.1

Explain the difference between the following pairs of terms:

  1. Counting loop and conditional loop.

  2. For statement and while statement.

  3. While statement and do-while statement.

  4. Zero indexing and unit indexing.

  5. Sentinel bound and limit bound.

  6. Counting bound and flag bound.

  7. Loop initializer and updater.

  8. Named constant and literal.

  9. Compound statement and null statement.

Exercise 6.2

Fill in the blank.

  1. The process of reading a data item before entering a loop is known as a _______.

  2. A loop that does nothing except iterate is an example of _______.

  3. A loop that contains no body is an example of a statement_______.

  4. A loop whose entry condition is stated as (k < 100 || k >= 0) would be an example of an ________ loop.

  5. A loop that should iterate until the user types in a special value should use a _______ bound.

  6. A loop that should iterate until its variable goes from 5 to 100 should use a _______ bound.

  7. A loop that should iterate until the difference between two values is less than 0.005 is an example of a _______bound.

Exercise 6.3

Identify the syntax errors in each of the following:

  1. for (int k = 0; k < 100; k++) System.out.println(k)

  2. for (int k = 0; k < 100; k++); System.out.println(k);

  3. int k = 0 while k < 100 {System.out.println(k); k++;}

  4. int k = 0; do {System.out.println(k); k++;} while k < 100 ;

Exercise 6.4

Determine the output and/or identify the error in each of the following code segments:

  1. for (int k = 1; k == 100; k += 2) System.out.println(k);

  2. int k = 0; while (k < 100) System.out.println(k); k++;

  3. for (int k = 0; k < 100; k++) ; System.out.println(k);


[Page 299]
Exercise 6.5

Write pseudocode algorithms for the following activities, paying particular attention to the initializer, updater, and boundary condition in each case.

  1. a softball game

  2. a five-question quiz

  3. looking up a name in the phone book

Exercise 6.6

Identify the pre- and postconditions for each of the statements that follow. Assume that all variables are int and have been properly declared.

  1. int result = x / y;

  2. int result = x % y;

  3. int x = 95; do x /= 2; while(x >= 0);

Exercise 6.7

Write three different loopsa for loop, a while loop, and a do-while loopto print all the multiples of 10, including 0, up to and including 1,000.

Exercise 6.8

Write three different loopsa for loop, a while loop, and a do-while loopto print the following sequence of numbers: 45, 36, 27, 18, 9, 0, -9, -18, -27, -36, -45.

Exercise 6.9

Write three different loopsa for loop, a while loop, and a do-while loopto print the following ski-jump design:

# # # # # # # # # # # # # # # # # # # # # # # # # # # # 


Exercise 6.10

The Straight Downhill Ski Lodge in Gravel Crest, Vermont, gets lots of college students on breaks. The lodge likes to keep track of repeat visitors. Straight Downhill's database includes an integer variable, visit, which gives the number of times a guest has stayed at the lodge (one or more). Write the pseudocode to catch those visitors who have stayed at the lodge at least twice and send them a special promotional package (pseudocode = send promo). (Note: The largest number of stays recorded is eight. The number nine is used as an end-of-data flag.)

Exercise 6.11

Modify your pseudocode in the preceding exercise. In addition to every guest who has stayed at least twice at the lodge receiving a promotional package, any guest with three or more stays should also get a $40 coupon good for lodging, lifts, or food.


[Page 300]
Exercise 6.12

Write a method that is passed a single parameter, N, and displays all the even numbers from 1 to N.

Exercise 6.13

Write a method that is passed a single parameter, N, that prints all the odd numbers from 1 to N.

Exercise 6.14

Write a method that is passed a single parameter, N, that prints all the numbers divisible by 10 from N down to 1.

Exercise 6.15

Write a method that is passed two parametersa char Ch and an int Nand prints a string of N Chs.

Exercise 6.16

Write a method that uses a nested for loop to print the following multiplication table:

  1  2  3  4  5  6  7  8  9 1 1 2 2  4 3 3  6  9 4 4  8 12 16 5 5 10 15 20 25 6 6 12 18 24 30 36 7 7 14 21 28 35 42 49 8 8 16 24 32 40 48 56 64 9 9 18 27 36 45 54 63 72 81 


Exercise 6.17

Write a method that uses nested for loops to print the patterns that follow. Your method should use the following statement to print the patterns: System.out.print('#').

# # # # # # # #   # # # # # # # #      # # # # # # # #   # # # # # # # #   # # # # # # #   # # # # # # #          #         #                 #     # # # # # #   # # # # # #              #     #                 #       # # # # #   # # # # #                  # #                 #         # # # #   # # # #                    # #               #           # # #   # # #                    #     #           #             # #   # #                    #         #       #               #   #                    # # # # # # # #   # # # # # # # # 


Exercise 6.18

Write a program that asks the user for the number of rows and the number of columns in a box of asterisks. Then use nested loops to generate the box.


[Page 301]
Exercise 6.19

Write a Java application that lets the user input a sequence of consecutive numbers. In other words, the program should let the user keep entering numbers as long as the current number is one greater than the previous number.

Exercise 6.20

Write a Java application that lets the user input a sequence of integers terminated by any negative value. The program should then report the largest and smallest values that were entered.

Exercise 6.21

How many guesses does it take to guess a secret number between 1 and N? For example, I'm thinking of a number between 1 and 100. I'll tell you whether your guess is too high or too low. Obviously, an intelligent first guess would be 50. If that's too low, an intelligent second guess would be 75. And so on. If we continue to divide the range in half, we'll eventually get down to one number. Because you can divide 100 seven times (50, 25, 12, 6, 3, 1, 0), it will take at most seven guesses to guess a number between 1 and 100. Write a Java applet that lets the user input a positive integer, N, and then reports how many guesses it would take to guess a number between 1 and N.

Exercise 6.22

Suppose you determine that the fire extinguisher in your kitchen loses X percent of its foam every day. How long before it drops below a certain threshold (Y percent), at which point it is no longer serviceable? Write a Java applet that lets the user input the values X and Y and then reports how many weeks the fire extinguisher will last.

Exercise 6.23

Leibnitz's method for computing p is based on the following convergent series:


How many iterations does it take to compute p to a value between 3.141 and 3.142 using this series? Write a Java program to find out.

Exercise 6.24

Newton's method for calculating the square root of N starts by making a (nonzero) guess at the square root. It then uses the original guess to calculate a new guess, according to the following formula:

guess = (( N / guess) + guess) / 2; 


No matter how wild the original guess is, if we repeat this calculation, the algorithm will eventually find the square root. Write a square root method based on this algorithm. Then write a program to determine how many guesses are required to find the square roots of different numbers. Uses Math.sqrt() to determine when to terminate the guessing.


[Page 302]
Exercise 6.25

Your employer is developing encryption software and wants you to develop a Java applet that will display all of the primes less than N, where N is a number to be entered by the user. In addition to displaying the primes themselves, provide a count of how many there are.

Exercise 6.26

Your little sister asks you to help her with her multiplication, and you decide to write a Java application that tests her skills. The program will let her input a starting number, such as 5. It will generate multiplication problems ranging from 5 x 1 to 5 x 12. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.

Exercise 6.27

Write an application that prompts the user for four values and draws corresponding bar graphs using an ASCII character. For example, if the user entered 15, 12, 9, and 4, the program would draw

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


Exercise 6.28

Revise the application in the preceding problem so that the bar charts are displayed vertically. For example, if the user inputs 5, 2, 3, and 4, the program should display

** **       ** **    ** ** ** ** ** ** ** ** ** ** ------------- 


Exercise 6.29

The Fibonacci sequence (named after the Italian mathematician Leonardo of Pisa, ca. 1200) consists of the numbers 0, 1, 1, 2, 3, 5, 8, 13, . . . in which each number (except for the first two) is the sum of the two preceding numbers. Write a method fibonacci(N) that prints the first N Fibonacci numbers.

Exercise 6.30

The Nuclear Regulatory Agency wants you to write a program that will help determine how long certain radioactive substances will take to decay. The program should let the user input two values: a string giving the substance's name and its half-life in years. (A substance's half-life is the number of years required for the disintegration of half of its atoms.) The program should report how many years it will take before there is less than 2 percent of the original number of atoms remaining.


[Page 303]
Exercise 6.31

Modify the CarLoan program so that it calculates a user's car payments for loans of different interest rates and different loan periods. Let the user input the amount of the loan. Have the program output a table of monthly payment schedules.

The next chapter also contains a number of loop exercises.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net