Java Reference
In-Depth Information
40.
If you look at the trace, you will see that after one iteration, the value of
sum
is
20. But the value should be 10 + 9, or 19. This should lead you to think that the
variable
n
is not decremented at the correct time. Indeed, the bug is that the two
statements
sum = sum + n;
n--;
should be reversed to
n--;
sum = sum + n;
41.
int
n, sum = 0;
for
(n = 1; n < 10; n++)
{
System.out.println("n == " + n + " sum == " + sum);
//Above line is a trace.
sum = sum + n;
}
System.out.println("After loop");
//trace
System.out.println("n == " + n + " sum == " + sum);
//trace
System.out.println("1 + 2 + ...+ 9 + 10 == " + sum);
If you study the output of this trace, you will see that 10 is never added in. This
is a bug in the loop.
42. This is the code you traced in the previous exercise. If you study the output of
this trace, you will see that 10 is never added in. This is an off-by-one error.
43.
assert
(time <= limit);
Programming Projects
Many of these Programming Projects can be solved using AW's CodeMate.
To access these please go to:
www.aw-bc.com/codemate
.
1.
(This is a version of an exercise from Chapter 2). The Babylonian algorithm to
compute the square root of a number
n
is as follows:
1. Make a guess at the answer (you can pick
n/2
as your initial guess).
2. Compute
r = n / guess
.
3. Set
guess = (guess +r) / 2
.
4. Go back to step 2 until the last two
guess
values are the same.
Write a program that inputs an integer for
n
, iterates through the Babylonian
algorithm until the
guess
is within 1% of the previous
guess
, and outputs the
answer as a
double
to two decimal places. Your answer should be accurate even
for large values of
n
.