Java Reference
In-Depth Information
c. 1 4 9 16 25 36 49 64 81 100
d. 0 0 0 0 0 0 0 0 0 0
e. 1 4 9 16 9 7 4 9 11
Use a loop when appropriate.
΢΢Exercise R7.8. Write a loop that fills an array a with 10 random numbers
between 1 and 100. Write code (using one or more loops) to fill a with 10
different random numbers between 1 and 100.
΢ Exercise R7.9. What is wrong with the following loop?
double[] data = new double[10];
for (int i = 1; i <= 10; i++) data[i] = i * i;
Explain two ways of fixing the error.
΢΢΢Exercise R7.10. Write a program that constructs an array of 20 integers
and fills the first ten elements with the numbers 1, 4, 9, ș, 100. Compile
it and launch the debugger. After the array has been filled with three
numbers, inspect it. What are the contents of the elements in the array
beyond those that you filled?
325
326
΢΢Exercise R7.11. Rewrite the following loops without using the Ȓfor eachȓ
construct. Here, data is an array of double values.
a. for (x : data) sum = sum + x ;
b. for (x : data) if (x == target) return true ;
c. int i = 0;
for (x : data) { data [i] = 2 * x; i++; }
΢΢Exercise R7.12. Rewrite the following loops, using the Ȓfor eachȓ
construct. Here, data is an array of double values.
a. for (int i = 0; i < data.length; i++) sum =
sum + data[i] ;
Search WWH ::




Custom Search