A selection statement specifies that an action is to be repeated while some condition remains true

  • Home
  • Textbooks
  • Java How to Program
  • Control Statements: Part 1

Problem 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: ______ ,______ and ______ .
b) The ______ 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 ______ repetition.
d) When it is not known in advance how many times a set of statements will be repeated, $a(n)$ ______ value can be used to terminate the repetition.
e) The ______ 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 ______ by default.
g) Java is a(n) ______ language- -it requires all variables to have a type.
h) If the increment operator is ______ to a variable, the variable is incremented by 1 first, then its new value is used in the expression.

Problem 2

State whether each of the following is true or $f$ alse. 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.
b) $\mathrm{A}$ set of statements contained within a pair of parentheses is called a block.
c) A selection statement specifies that an action is to be repeated while some condition remains true.
d) A nested control statement appears in the body of another control statement.
e) Java provides the arithmetic compound assignment operators $+=,-=,^{2}=, \quad /=$ and $\aleph=$ for abbreviating assignment cxpressions.
The primitive types (boolean, char, byte, short, int, long, float and double) are portable across only Windows platforms.
g) Specifying the order in which statements (actions) execute in a program is called program control.
h) The unary cast operator (double) creates a temporary integer copy of its operand.
i) Instance variables of type boolean are given the value true by default.
j) Pseudocode helps a programmer think out a program before attempting to write it in a programming language.

Problem 3

Write four different Java statements that cach add 1 to integer variable x.

Problem 4

Write Java statements to accomplish cach of the following tasks:
a) Assign the sum of $x$ and $y$ to $z,$ and increment $x$ by 1 after the calculation. Use only one statement.
b) Test whether variable count is greater than $10 .$ If it is, print "Count is greater than $10 "$
c) Decrement the variable $x$ by 1 , then subtract it from the variable total. Use only one statement.
d) Calculate the remainder after $q$ is divided by divisor, and assign the result to q. Write this statement in two different ways.

Problem 5

Write a Java statement to accomplish each of the following tasks:
a) Declare variables sum and $x$ to be of type int.
b) Assign 1 to variable x.
c) Assign 0 to variable sum.
d) Add variable $\times$ to variable sum, and assign the result to variable sum.
e) Print "The sum is: ", followed by the value of variable sum.

Problem 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.

Problem 7

Determine the value of the variables in the following statement after the calculation is performed. Assume that when the statement begins executing, all variables are type int and have the value 5

Problem 8

Identify and correct the errors in each of the following sets of code:

Problem 9

What is wrong with the following while statement?

Problem 10

Compare and contrast the if single-selection statement and the while repetition statement. How are these two statements similar? How are they different?

Problem 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 a programmer avoid that outcome?

Problem 12

Describe the two ways in which control statements can be combined.

Problem 13

What type of repetition would be appropriate for calculating the sum of the first 100 positive integers? What type of repetition would be appropriate for calculating the sum of an arbitrary number of positive integers? Briefly describe how each of these tasks could be performed.

Problem 14

What is the difference between preincrementing and postincrementing a variable?

Problem 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.

Problem 17

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.
Drivers are concerned with the mileage their automobiles get. One driver has kept track of several tankfuls of gasoline 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 tankful. The program should calculate and display the miles per gallon obtained for each tankful and print the combined miles per gallon obtained for all tankfuls 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.

Problem 18

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.
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 these facts as integers, calculate the new balance ( = brginming balance
$+\text { duarges }-\text { 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 1 imit exceeded".

Problem 19

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.
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 $\$ 5000$ worth of merchandise in a weck receives $\$ 200$ plus $9 \%$ of $\$ 5000,$ or a total of $\$ 650 .$ You have been supplied with a list of the items sold by each salesperson. The values of these items are as follows:

Problem 20

Develop a Java application that will determine 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 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee and should determine and display the employee's gross pay. Use class Scanner to input the data.

Problem 21

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 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.

Problem 22

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

Problem 23

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.]

Problem 24

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.

Problem 27

(Datngling-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 .$ Note that the compiler ignores the indentation in a Java program. Also, the Java compiler always associates an el se with the immediately preceding if unless told to do otherwise by the placement of braces ( $(y)$ ). On first glance, the programmer may not be sure which if an else matches - this situarion is referred to as the "dangling-else problem." We have eliminated the indentation from the following code to make the problem more challenging. $[\text {Hint: Apply the indentation conventions you have learned.}]$

Problem 28

$(\text {Another Dangling-e7se 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 have eliminated the indentation from the given code to make the problem more challenging. $[\text {Note}:$ It is possible that no modification is necessary for some of the parts.]

Problem 29

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 berween 1 and 20 .

Problem 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 is a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value.

Problem 31

Write an application that inputs an integer containing only 0 s and 1 s (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 has 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 has 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.1

Problem 32

Write an application that uses only the output statements
to display the checkerboard pattern that follows. Note that a System.out.print The method call with no arguments causes the program to output a single newline character. [Hint: Repetition statements are required.]

Problem 33

Write an application that keeps displaying in the command window the multiples of the integer $2-$ namely, $2,4,8,16,32,6 \overline{4},$ and so on. Your loop should not terminate (i.e., create an infinite loop). What happens when you run this program?

Problem 34

What is wrong with the following starement? Provide the correct statement to add one to the sum of $x$ and $y$
System.out.println( $++(x+y))$

Problem 35

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.

Problem 36

Write an application that reads three nonzero integers and determines and prints whether they could represent the sides of a right triangle.

Problem 37

A company wants to transmit data over the telephone but is concerned that its phones may be tapped. It has asked you to write a program that will encrypt the data 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 to form the original number.

Problem 38

The factorial of a nonnegative integer $n$ is written as $n !$ (pronounced "n factorial") and is defined as follows:
$n !=n \cdot(n-1) \cdot(n-2) \dots \dots 1 \quad \text { (for values of } n \text { greater than or equal to } 1)$
and
\[
n !=1 \quad(\text { for } n=0)
\]
For example, $5 !=5 \cdot 4 \cdot 3 \cdot 2 \cdot 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 formula
\[
e=1+\frac{1}{1 !}+\frac{1}{2 !}+\frac{1}{3 !}+\dots
\]
c) Write an application that compures the value of $e^{x}$ by using the formula
\[
e^{x}=1+\frac{x}{1 !}+\frac{x^{2}}{2 !}+\frac{x^{3}}{3 !}+\ldots
\]

What value can be used to terminate the repetition?

c) Repeating a set of instructions a specific number of times is called repetition. ANS: counter-controlled (or definite). d) When it is not known in advance how many times a set of statements will be repeated, a(n) value can be used to terminate the repetition.

What type of repetition would be appropriate for calculating the sum of arbitrary number of positive numbers?

The sentinel controlled repetition would be appropriate for calculating the sum of an arbitrary number of positive integers.

Is a set of statements that execute in the order that they appear?

A sequence structure is a set of statements that execute in the order that they appear.

Toplist

Neuester Beitrag

Stichworte