6.1 a) for
, while
. b) after. c) switch
. d) continue
. e) &&
(conditional AND) or &
(boolean logical AND). f) false
. g) static
.
6.2 a) False. The default
label is optional. If no default action is needed, then there’s no need for a default
label. b) False. You could terminate the case
with other statements, such as a return
. False. Both of the relational expressions must be true for this entire expression to be true when using the &&
operator. d) True. e) True. f) False. The switch
statement does not provide a mechanism for testing ranges of values, so you must list every value to test in a separate case
label. g) True.
6.3 The answers to Self-Review Exercise 6.3 are as follows:
sum = 0;
for (count = 1; count <= 99; count += 2)
{
sum += count
}
double result = Math.Pow(2.5, 3);
i = 1;
while (i <= 20)
{
Console.Write(i);
if (i % 5 == 0)
{
Console.WriteLine();
}
else
{
Console.Write(' ');
}
++i;
}
for (i = 1; i <= 20; ++i)
{
Console.Write(i);
if (i % 5 == 0)
{
Console.WriteLine();
}
else
{
Console.Write(' ');
}
}
6.4 The answers to Self-Review Exercise 6.4 are as follows:
Error: The semicolon after the while
header causes an infinite loop, and there’s a missing left brace for the body of the while
statement.
Correction: Remove the semicolon and add a {
before the loop’s body.
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)
{
Console.WriteLine((double) k / 10);
}
Error: case 1
cannot fall through into case 2
.
Correction: Terminate the case
in some way, such as adding a break
statement at the end of the statements for the first case
.
Error: The wrong operator is used in the while
iteration-continuation condition. Correction: Use <=
rather than <
, or change 10
to 11
.