Self-Review Exercises 4.1 Fill in the blanks in each of the following statements: a) All programs can be written in terms of three types of control structures: sequence statement, selection statement and repetition statement. b) The if…else statement is used to execute one action when a condition is true and another when that condition is false. c) Repeating a set of instructions a specific number of times is called counter-controlled (or definite) repetition. d) When it’s not known in advance how many times a set of statements will be repeated, a(n) sentinel (signal, flag or dummy) value can be used to terminate the repetition. e) The sequence structure is built into Java; by default, statements execute in the order they appear. f) Instance variables of types char, byte, short, int, long, float and double are all given the value 0(zero) by default. g) Java is a(n) strongly typed language; it requires all variables to have a type. h) If the increment operator is prefixed to a variable, first the variable is incremented by 1, then its new value is used in the expression. 4.2 State whether each of the following is true or false. If false, explain why. a) An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which they execute. (T) b) A set of statements contained within a pair of parentheses is called a block. (F) c) A selection statement specifies that an action is to be repeated while some condition remains true. (F) d) A nested control statement appears in the body of another control statement. (T) e) Java provides the arithmetic compound assignment operators +=, -=, *=, /= and %= for abbreviating assignment expressions. (T) f) The primitive types (boolean, char, byte, short, int, long, float and double) are portable across only Windows platforms. (F) g) Specifying the order in which statements execute in a program is called program control. (T) h) The unary cast operator (double) creates a temporary integer copy of its operand. (F) i) Instance variables of type boolean are given the value true by default. (F) j) Pseudocode helps you think out a program before attempting to write it in a programming language. (T) 4.3 Write four different Java statements that each add 1 to integer variable x. Answer: x = x + 1; x += 1; x++; ++x 4.4 Write Java statements to accomplish each of the following tasks: a) Use one statement to assign the sum of x and y to z, then increment x by 1. (z = y + x++) b) Test whether variable count is greater than 10. If it is, print "Count is greater than 10". c) Use one statement to decrement the variable x by 1, then subtract it from variable total and store the result in variable total. d) Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways. 4.5 Write a Java statement to accomplish each of the following tasks: a) Declare variables sum of type int and initialize it to 0. b) Declare variables x of type int and initialize it to 1. c) Add variable x to variable sum, and assign the result to variable sum. d) Print "The sum is: ", followed by the value of variable sum. 4.6 Combine the statements that you wrote in Exercise 4.5 into a Java application that calculates and prints the sum of the integers from 1 to 10. Use a while statement to loop through the calculation and increment statements. The loop should terminate when the value of x becomes 11. 4.7 Determine the value of the variables in the statement product *= x++; after the calculation is performed. Assume that all variables are type int and initially have the value 5. (product: 25, x: 6) 4.8 Identify and correct the errors in each of the following sets of code: a) while (c <= 5) { product *= c; ++c; b) if (gender == 1) System.out.println("Woman"); else; System.out.println("Man"); 4.9 What is wrong with the following while statement? while (z >= 0) sum += z; Exercises 4.10 Compare and contrast the if single-selection statement and the while repetition statement. How are these two statements similar? How are they different? 4.11 Explain what happens when a Java program attempts to divide one integer by another. What happens to the fractional part of the calculation? How can you avoid that outcome? 4.12 Describe the two ways in which control statements can be combined. 4.13 What type of repetition would be appropriate for calculating the sum of the first 100 positive integers? What type would be appropriate for calculating the sum of an arbitrary number of positive integers? Briefly describe how each of these tasks could be performed. 4.14 What is the difference between preincrementing and postincrementing a variable? 4.15 Identify and correct the errors in each of the following pieces of code. [Note: There may be more than one error in each piece of code.] a) if (age >= 65); System.out.println("Age is greater than or equal to 65"); else System.out.println("Age is less than 65)"; b) int x = 1, total; while (x <= 10) { total += x; ++x; } c) while (x <= 100) total += x; ++x; d) while (y > 0) { System.out.println(y); ++y; 4.16 What does the following program print? 1 // Exercise 4.16: Mystery.java 2 public class Mystery 3 { 4 public static void main(String[] args) 5 { 6 int x = 1; 7 int total = 0; 89 while (x <= 10) 10 { 11 int y = x * x; 12 System.out.println(y); 13 total += y; 14 ++x; 15 } 16 17 System.out.printf("Total is %d%n", total); 18 } 19 } // end class Mystery For Exercise 4.17 through Exercise 4.20, perform each of the following steps: a) Read the problem statement. b) Formulate the algorithm using pseudocode and top-down, stepwise refinement. c) Write a Java program. d) Test, debug and execute the Java program. e) Process three complete sets of data. 4.17 (Gas Mileage) Drivers are concerned with the mileage their automobiles get. One driver has kept track of several trips by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should produce floating-point results. Use class Scanner and sentinel-controlled repetition to obtain the data from the user. 4.18 (Credit Limit Calculator) Develop a Java application that determines 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 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". 4.19 (Sales Commission Calculator) A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5,000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You’ve been supplied with a list of the items sold by each salesperson. The values of these items are as follows: Item Value 1 239.99 2 129.75 3 99.95 4 350.89 Develop a Java application that inputs one salesperson’s items sold for last week and calculates and displays that salesperson’s earnings. There’s no limit to the number of items that can be sold. 4.20 (Salary Calculator) Develop a Java application that determines the gross pay for each of three employees. The company pays straight time for the first 40 hours worked by each employee and time and a half for all hours worked in excess of 40. You’re given a list of the employees, their number of hours worked last week and their hourly rates. Your program should input this information for each employee, then determine and display the employee’s gross pay. Use class Scanner to input the data. 4.21 (Find the Largest Number) The process of finding the largest value 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, then a Java application that inputs a series of 10 integers and determines and prints the largest integer. 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. 4.22 (Tabular Output) 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 4.23 (Find the Two Largest Numbers) Using an approach similar to that for Exercise 4.21, find the two largest values of the 10 values entered. [Note: You may input each number only once.] 4.24 (Validating User Input) Modify the program in Fig. 4.12 to validate its inputs. For any input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value. 4.25 What does the following program print? 1 // Exercise 4.25: Mystery2.java 2 public class Mystery2 3 { 4 public static void main(String[] args) 5 { 6 int count = 1; 78 while (count <= 10) 9 { 10 System.out.println(count % 2 == 1 ? "****" : "++++++++"); 11 ++count; 12 } 13 } 14 } // end class Mystery2 4.26 What does the following program print? 1 // Exercise 4.26: Mystery3.java 2 public class Mystery3 3 { 4 public static void main(String[] args) 5 { 6 int row = 10; 78 while (row >= 1) 9 { 10 int column = 1; 11 12 while (column <= 10) 13 { 14 System.out.print(row % 2 == 1 ? "<" : ">"); 15 ++column; 16 } 17 18 --row; 19 System.out.println(); 20 } 21 } 22 } // end class Mystery3 4.27 (Dangling-else Problem) Determine the output for each of the given sets of code when x is 9 and y is 11 and when x is 11 and y is 9. The compiler ignores the indentation in a Java program. Also, the Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({}). On first glance, you may not be sure which if a particular else matches—this situation is referred to as the “dangling-else problem.” We’ve eliminated the indentation from the following code to make the problem more challenging. [Hint: Apply the indentation conventions you’ve learned.] a) if (x < 10) if (y > 10) System.out.println("*****"); else System.out.println("#####"); System.out.println("$$$$$"); b) if (x < 10) { if (y > 10) System.out.println("*****"); } else { System.out.println("#####"); System.out.println("$$$$$"); } 4.28 (Another Dangling-else Problem) Modify the given code to produce the output shown in each part of the problem. Use proper indentation techniques. Make no changes other than inserting braces and changing the indentation of the code. The compiler ignores indentation in a Java program. We’ve eliminated the indentation from the given code to make the problem more challenging. [Note: It’s possible that no modification is necessary for some of the parts.] if (y == 8) if (x == 5) System.out.println("@@@@@"); else System.out.println("#####"); System.out.println("$$$$$"); System.out.println("&&&&&"); a) Assuming that x = 5 and y = 8, the following output is produced: @@@@@ $$$$$ &&&&& b) Assuming that x = 5 and y = 8, the following output is produced: @@@@@ c) Assuming that x = 5 and y = 8, the following output is produced: @@@@@ d) Assuming that x = 5 and y = 7, the following output is produced. [Note: The last three output statements after the else are all part of a block.] ##### $$$$$ &&&&& 4.29 (Square of Asterisks) Write an application that prompts the user to enter the size of the side of a square, then displays a hollow square of that size made of asterisks. Your program should work for squares of all side lengths between 1 and 20. 4.30 (Palindromes) A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following 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’s a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value. 4.31 (Printing the Decimal Equivalent of a Binary Number) Write an application that inputs an integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use the remainder and division operators to pick off the binary number’s digits one at a time, from right to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left a positional value of 10, then 100, then 1000, and so on. The decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left a positional value of 2, then 4, then 8, and so on. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13.] 4.32 (Checkerboard Pattern of Asterisks) Write an application that uses only the output statements System.out.print("* "); System.out.print(" "); System.out.println(); to display the checkerboard pattern that follows. A System.out.println method call with no arguments causes the program to output a single newline character. [Hint: Repetition statements are required.] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 4.33 (Multiples of 2 with an Infinite Loop) Write an application that keeps displaying in the command window the multiples of the integer 2—namely, 2, 4, 8, 16, 32, 64, and so on. Your loop should not terminate (i.e., it should create an infinite loop). What happens when you run this program? 4.34 (What’s Wrong with This Code?) What is wrong with the following statement? Provide the correct statement to add one to the sum of x and y. System.out.println(++(x + y)); 4.35 (Sides of a Triangle) Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle. 4.36 (Sides of a Right Triangle) Write an application that reads three nonzero integers and determines and prints whether they could represent the sides of a right triangle. 4.37 (Factorial) The factorial of a nonnegative integer n is written as n! (pronounced “n factorial”) and is defined as follows: n! = n · (n – 1) · (n – 2) · … · 1 (for values of n greater than or equal to 1) and n! = 1 (for n = 0) For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. a) Write an application that reads a nonnegative integer and computes and prints its factorial. b) Write an application that estimates the value of the mathematical constant e by using the following formula. Allow the user to enter the number of terms to calculate. c) Write an application that computes the value of ex by using the following formula. Allow the user to enter the number of terms to calculate. Making a Difference 4.38 (Enforcing Privacy with Cryptography) The explosive growth of Internet communications and data storage on Internet-connected computers has greatly increased privacy concerns. The field of cryptography is concerned with coding data to make it difficult (and hopefully—with the most advanced schemes—impossible) for unauthorized users to read. In this exercise you’ll investigate a simple scheme for encrypting and decrypting data. A company that wants to send data over the Internet has asked you to write a program that will encrypt it so that it may be transmitted more securely. All the data is transmitted as four-digit integers. Your application should read a four-digit integer entered by the user and encrypt it as follows: Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer. Write a separate application that inputs an encrypted four-digit integer and decrypts it (by reversing the encryption scheme) to form the original number. [Optional reading project: Research “public key cryptography” in general and the PGP (Pretty Good Privacy) specific public key scheme. You may also want to investigate the RSA scheme, which is widely used in industrial-strength applications.]
4.39 (World Population Growth) World population has grown considerably over the centuries. Continued growth could eventually challenge the limits of breathable air, drinkable water, arable cropland and other limited resources. There’s evidence that growth has been slowing in recent years and that world population could peak some time this century, then start to decline. For this exercise, research world population growth issues online. Be sure to investigate various viewpoints. Get estimates for the current world population and its growth rate (the percentage by which it’s likely to increase this year). Write a program that calculates world population growth each year for the next 75 years, using the simplifying assumption that the current growth rate will stay constant. Print the results in a table. The first column should display the year from year 1 to year 75. The second column should display the anticipated world population at the end of that year. The third column should display the numerical increase in the world population that would occur that year. Using your results, determine the year in which the population would be double what it is today, if this year’s growth rate were to persist.
|