Self-Review Exercises 5.1 Fill in the blanks in each of the following statements: a) Typically, for statements are used for counter-controlled repetition and while statements for sentinel-controlled repetition. b) The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. c) The switch statement selects among multiple actions based on the possible values of an integer variable or expression, or a String. d) The continue statement, when executed in a repetition statement, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. e) The conditional and (&&) operator can be used to ensure that two conditions are both true before choosing a certain path of execution. f) If the loop-continuation condition in a for header is initially false, the program does not execute the for statement’s body. g) Methods that perform common tasks and do not require objects are called static methods. 5.2 State whether each of the following is true or false. If false, explain why. a) The default case is required in the switch selection statement. (F) b) The break statement is required in the last case of a switch selection statement. (F) c) The expression ((x > y) && (a < b)) is true if either x > y is true or a < b is true. (F) d) An expression containing the || operator is true if either or both of its operands are true. (T) e) The comma (,) formatting flag in a format specifier (e.g., %,20.2f) indicates that a value should be output with a thousands separator. (F) f) To test for a range of values in a switch statement, use a hyphen (–) between the start and end values of the range in a case label. (F) Explaination: The switch statement does not provide a mechanism for testing ranges of values, so every value that must be tested should be listed in a separate case label g) Listing cases consecutively with no statements between them enables the cases to perform the same set of statements. (T) 5.3 Write a Java statement or a set of Java statements to accomplish each of the following tasks: a) Sum the odd integers between 1 and 99, using a for statement. Assume that the integer variables sum and count have been declared. b) Calculate the value of 2.5 raised to the power of 3, using the pow method. c) Print the integers from 1 to 20, using a while loop and the counter variable i. Assume that the variable i has been declared, but not initialized. Print only five integers per line. [Hint: Use the calculation i % 5. When the value of this expression is 0, print a newline character; otherwise, print a tab character. Assume that this code is an application. Use the System.out.println() method to output the newline character, and use the System.out.print('\t') method to output the tab character.] d) Repeat part (c), using a for statement. 5.4 Find the error in each of the following code segments, and explain how to correct it: a) i = 1; while (i <= 10); ++i; } b) for (k = 0.1; k != 1.0; k += 0.1) System.out.println(k); Answer: Error: Using a floating-point number to control a for statement may not work, because floating-point numbers are represented only approximately by most computers. Correction: Use an integer, and perform the proper calculation in order to get the values you desire: for (k = 1; k != 10; k++) System.out.println((double) k / 10); c) switch (n) { case 1: System.out.println("The number is 1"); case 2: System.out.println("The number is 2"); break; default: System.out.println("The number is not 1 or 2"); break; } d) The following code should print the values 1 to 10: n = 1; while (n < 10) System.out.println(n++); Exercises 5.5 Describe the four basic elements of counter-controlled repetition. 5.6 Compare and contrast the while and for repetition statements. 5.7 Discuss a situation in which it would be more appropriate to use a do…while statement than a while statement. Explain why. 5.8 Compare and contrast the break and continue statements. 5.9 Find and correct the error(s) in each of the following segments of code: a) For (i = 100, i >= 1, i++) System.out.println(i); b) The following code should print whether integer value is odd or even: switch (value % 2) { case 0: System.out.println("Even integer"); case 1: System.out.println("Odd integer"); } c) The following code should output the odd integers from 19 to 1: for (i = 19; i >= 1; i += 2) System.out.println(i); d) The following code should output the even integers from 2 to 100: counter = 2; do { System.out.println(counter); counter += 2; } While (counter < 100); 5.10 What does the following program do? 1 // Exercise 5.10: Printing.java 2 public class Printing 3 { 4 public static void main(String[] args) 5 { 6 for (int i = 1; i <= 10; i++) 7 { 8 for (int j = 1; j <= 5; j++) 9 System.out.print('@'); 10 11 System.out.println(); 12 } 13 } 14 } // end class Printing 5.11 (Find the Smallest Value) Write an application that finds the smallest of several integers. Assume that the first value read specifies the number of values to input from the user. 5.12 (Calculating the Product of Odd Integers) Write an application that calculates the product of the odd integers from 1 to 15. 5.13 (Factorials) Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. Write an application that calculates the factorials of 1 through 20. Use type long. Display the results in tabular format. What difficulty might prevent you from calculating the factorial of 100? 5.14 (Modified Compound-Interest Program) Modify the compound-interest application of Fig. 5.6 to repeat its steps for interest rates of 5%, 6%, 7%, 8%, 9% and 10%. Use a for loop to vary the interest rate. 5.15 (Triangle Printing Program) Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print('*'); which causes the asterisks to print side by side. A statement of the form System.out.println(); can be used to move to the next line. A statement of the form System.out.print(' '); can be used to display a space for the last two patterns. There should be no other output statements in the program. [Hint: The last two patterns require that each line begin with an appropriate number of blank spaces.] (a) (b) (c) (d) * ********** ********** * ** ********* ********* ** *** ******** ******** *** **** ******* ******* **** ***** ****** ****** ***** ****** ***** ***** ****** ******* **** **** ******* ******** *** *** ******** ********* ** ** ********* ********** * * ********** 5.16 (Bar Chart Printing Program) One interesting application of computers is to display graphs and bar charts. Write an application that reads five numbers between 1 and 30. For each number that’s read, your program should display the same number of adjacent asterisks. For example, if your program reads the number 7, it should display *******. Display the bars of asterisks after you read all five numbers. 5.17 (Calculating Sales) An online retailer sells five products whose retail prices are as follows: Product 1, $2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49 and product 5, $6.87. Write an application that reads a series of pairs of numbers as follows: a) product number b) quantity sold Your program should use a switch statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold. Use a sentinel-controlled loop to determine when the program should stop looping and display the final results. 5.18 (Modified Compound-Interest Program) Modify the application in Fig. 5.6 to use only integers to calculate the compound interest. [Hint: Treat all monetary amounts as integral numbers of pennies. Then break the result into its dollars and cents portions by using the division and remainder operations, respectively. Insert a period between the dollars and the cents portions.] 5.19 Assume that i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? a) System.out.println(i == 1); b) System.out.println(j == 3); c) System.out.println((i >= 1) && (j < 4)); d) System.out.println((m <= 99) & (k < m)); e) System.out.println((j >= i) || (k == m)); f) System.out.println((k + m < j) | (3 - j >= k)); g) System.out.println(!(k > m)); 5.20 (Calculating the Value of π) Calculate the value of π from the infinite series π = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + … Print a table that shows the value of π approximated by computing the first 200,000 terms of this series. How many terms do you have to use before you first get a value that begins with 3.14159? 5.21 (Pythagorean Triples) A right triangle can have sides whose lengths are all integers. The set of three integer values for the lengths of the sides of a right triangle is called a Pythagorean triple. The lengths of the three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an application that displays a table of the Pythagorean triples for side1, side2 and the hypotenuse, all no larger than 500. Use a triple-nested for loop that tries all possibilities. This method is an example of “brute-force” computing. You’ll learn in more advanced computer science courses that for many interesting problems there’s no known algorithmic approach other than using sheer brute force. 5.22 (Modified Triangle Printing Program) Modify Exercise 5.15 to combine your code from the four separate triangles of asterisks such that all four patterns print side by side. [Hint: Make clever use of nested for loops.] 5.23 (De Morgan’s Laws) In this chapter, we discussed the logical operators &&, &, ||, |, ^ and !. De Morgan’s laws can sometimes make it more convenient for us to express a logical expression. These laws state that the expression !(condition1 && condition2) is logically equivalent to the expression (!condition1 || !condition2). Also, the expression !(condition1 || condition2) is logically equivalent to the expression (!condition1 && !condition2). Use De Morgan’s laws to write equivalent expressions for each of the following, then write an application to show that both the original expression and the new expression in each case produce the same value: a) !(x < 5) && !(y >= 7) b) !(a == b) || !(g != 5) c) !((x <= 8) && (y > 4)) d) !((i > 4) || (j <= 6)) 5.24 (Diamond Printing Program) Write an application that prints the following diamond shape. You may use output statements that print a single asterisk (*), a single space or a single newline character. Maximize your use of repetition (with nested for statements), and minimize the number of output statements. * *** ***** ******* ********* ******* ***** *** * 5.25 (Modified Diamond Printing Program) Modify the application you wrote in Exercise 5.24 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond. Your program should then display a diamond of the appropriate size. 5.26 A criticism of the break statement and the continue statement is that each is unstructured. Actually, these statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you’d remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement exits a loop from the body of the loop. The other way to exit is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates “early exit because of a ‘break’ condition.”] Use the technique you develop here to remove the break statement from the application in Fig. 5.13. 5.27 What does the following program segment do? for (i = 1; i <= 5; i++) { for (j = 1; j <= 3; j++) { for (k = 1; k <= 4; k++) System.out.print('*'); System.out.println(); } // end inner for System.out.println(); } // end outer for 5.28 Describe in general how you’d remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the technique you develop here to remove the continue statement from the program in Fig. 5.14. 5.29 (“The Twelve Days of Christmas” Song) Write an application that uses repetition and switch statements to print the song “The Twelve Days of Christmas.” One switch statement should be used to print the day (“first,” “second,” and so on). A separate switch statement should be used to print the remainder of each verse. Visit the website en.wikipedia.org/wiki/The_Twelve_Days_ of_Christmas_(song) for the lyrics of the song. 5.30 (Modified AutoPolicy Class) Modify class AutoPolicy in Fig. 5.11 to validate the two-letter state codes for the northeast states. The codes are: CT for Connecticut, MA for Massachusetts, ME for Maine, NH for New Hampshire, NJ for New Jersey, NY for New York, PA for Pennsylvania and VT for Vermont. In AutoPolicy method setState, use the logical OR (||) operator (Section 5.9) to create a compound condition in an if…else statement that compares the method’s argument with each two-letter code. If the code is incorrect, the else part of the if…else statement should display an error message. In later chapters, you’ll learn how to use exception handling to indicate that a method received an invalid value. Making a Difference 5.31 (Global Warming Facts Quiz) The controversial issue of global warming has been widely publicized by the film “An Inconvenient Truth,” featuring former Vice President Al Gore. Mr. Gore and a U.N. network of scientists, the Intergovernmental Panel on Climate Change, shared the 2007 Nobel Peace Prize in recognition of “their efforts to build up and disseminate greater knowledge about man-made climate change.” Research both sides of the global warming issue online (you might want to search for phrases like “global warming skeptics”). Create a five-question multiplechoice quiz on global warming, each question having four possible answers (numbered 1–4). Be objective and try to fairly represent both sides of the issue. Next, write an application that administers the quiz, calculates the number of correct answers (zero through five) and returns a message to the user. If the user correctly answers five questions, print “Excellent”; if four, print “Very good”; if three or fewer, print “Time to brush up on your knowledge of global warming,” and include a list of some of the websites where you found your facts. 5.32 (Tax Plan Alternatives; The “FairTax”) There are many proposals to make taxation fairer. Check out the FairTax initiative in the United States at www.fairtax.org. Research how the proposed FairTax works. One suggestion is to eliminate income taxes and most other taxes in favor of a 23% consumption tax on all products and services that you buy. Some FairTax opponents question the 23% figure and say that because of the way the tax is calculated, it would be more accurate to say the rate is 30%—check this carefully. Write a program that prompts the user to enter expenses in various expense categories they have (e.g., housing, food, clothing, transportation, education, health care, vacations), then prints the estimated FairTax that person would pay. 5.33 (Facebook User Base Growth) According to CNNMoney.com, Facebook hit one billion users in October 2012. Using the compound-growth technique you learned in Fig. 5.6 and assuming its user base grows at a rate of 4% per month, how many months will it take for Facebook to grow its user base to 1.5 billion users? How many months will it take for Facebook to grow its user base to two billion users? |