C.8 Fill in the blanks in each of the following statements:
a) Typically, _____________statements are used for counter-controlled repetition and _____________statements for sentinel-controlled repetition.
b) The do
...while
statement tests the loop-continuation condition _____________executing the loop’s body; therefore, the body always executes at least once.
c) The _____________statement selects among multiple actions based on the possible values of an integer variable or expression.
d) The _____________operator can be used to ensure that two conditions are both true before choosing a certain path of execution.
e) If the loop-continuation condition in a for
header is initially _____________, the program does not execute the for
statement’s body.
C.9 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.
b) The break
statement is required in the last case of a switch
selection statement.
c) The expression ( ( x > y ) && ( a < b ) )
is true if either x > y
is true or a < b
is true.
d) An expression containing the ||
operator is true if either or both of its operands are true.
e) Listing cases consecutively with no statements between them enables the cases to perform the same set of statements.
C.10 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( ' ' )
method to output the tab character.]
d) Repeat part (c), using a for
statement.
C.11 Find the error in each of the following code segments, and explain how to correct it:
a) i =
1
;
while ( i <= 10 );
++i;
}
for ( k = 0.1; k != 1.0; k += 0.1 )
System.out.println( k );
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++ );