Unit 1?Getting Started with Java

Unit 1?Getting Started with Java. Chapter 4? Introduction to Control Statements
. EXERCISE 4.1. 1. a. x *= 2;. b. y %= 2;. 2. a. x = x + 5;. b. x = x * x;. exercise 4.2.
1. a. 2. b. 4. c. 64. d. 2. 2. ... This code inputs an arbitrary number of numbers from
the user and computes and displays their product. int limit = 10, count = 1;.

Part of the document


Unit 1-Getting Started with Java

Chapter 4- Introduction to Control Statements


EXERCISE 4.1

1.
a. x *= 2;
b. y %= 2;
2.
a. x = x + 5;
b. x = x * x;

exercise 4.2

1.
a. 2
b. 4
c. 64
d. 2
2. Both answers assume that rand refers to an instance of class Random.
a. System.out.println(1 + generator.nextInt(20));
b. System.out.println(1 + 10 * generator.nextDouble());

EXERCISE 4.3

1. Jill uses a while statement in her instructions because there might be
more than one cow to milk.
2. Jill uses an if-else statement in her instructions because there are
two different types of cows, leading to two different cases (colors of
buckets) for depositing the milk.
a.
if (the piece is red)
put it on a red square
else
put it on a black square
b.
if (your shoes are muddy)
take them off and leave them outside the door
c.
while (there are more marbles on the floor){
pick a marble up off the floor
put the marble in a bag
3.
a. This statement leaves the larger value in y and the smaller value
in x.
b. This statement inputs a user-specified number of integers and
outputs the average of their absolute values.

EXERCISE 4.4

1. The condition of an if statement must contain a Boolean expression.
2. The curly braces enclose a sequence of statements that are treated as
a logical unit.
3. An if statement provides a one-way decision. A single action is
executed if the condition is true; otherwise, control proceeds to the
next statement after the if statement. An if-else statement provides a
two-way decision. The action following the condition is executed if
the condition is true; otherwise, the action after the else is
executed.
4.
a. true
b. true
c. false
5.
a. x > 0
b. numSeconds == 60
c. c == Math.round(Math.sqrt(a * a + b * b))
6.
a. 5
b. Equal
7.
a.
if (x > y)
System.out.println(x);
else
System.out.println(y);
b.
System.out.print("Enter the first whole number: ");
x = reader.nextInt();
System.out.print("Enter the second whole number: ");
y = reader.nextInt();
if (x > y){ // if true, we need to exchange x and y
temp = y;
y = x;
x = temp;
}
System.out.println(x);
System.out.println(y);

EXERCISE 4.5

1. A while loop terminates its execution when its condition becomes
false.
2. The three components of a while loop are the continuation condition,
loop body statements, and update statements.
3. The body of the loop does not execute.
4.
a. This code displays the powers of 2 from 1 to 10.
b. This code inputs an arbitrary number of numbers from the user and
computes and displays their product.
5.
a.
int limit = 10, count = 1;
while (count