Java Reference
In-Depth Information
Self-Test Exercises
28. What is the output of the following?
for
(
int
count = 1; count < 5; count++)
System.out.print((2 * count) + " ");
29. What is the output of the following?
for
(
int
n = 10; n > 0; n = n - 2)
System.out.println("Hello " + n);
30. What is the output of the following?
for
(
double
sample = 2; sample > 0; sample = sample - 0.5)
System.out.print(sample + " ");
31. Rewrite the following
for
statement as a
while
loop (and possibly some addi-
tional statements):
int
n;
for
(n = 10; n > 0; n = n - 2)
System.out.println("Hello " + n);
32. What is the output of the following loop? Identify the connection between the
value of
n
and the value of the variable
log
.
int
n = 1024;
int
log = 0;
for
(
int
i = 1; i < n; i = i * 2)
log++;
System.out.println(n + " " + log);
33. What is the output of the following loop? Comment on the code. (This is not
the same as the previous exercise.)
int
n = 1024;
int
log = 0;
for
(
int
i = 1; i < n; i = i * 2);
log++;
System.out.println(n + " " + log);
34. Predict the output of the following nested loops:
int
n, m;
for
(n = 1; n <= 10; n++)
for
(m = 10; m >= 1; m- -)
System.out.println(n + " times " + m
+ " = " + n*m);