Java Reference
In-Depth Information
3. int[] odds = new int[22];
for (int i = 0; i < 22; i++) {
odds[i] = i * 2 - 5;
}
4. {0, 4, 11, 0, 44, 0, 0, 2}
5. The code to print the arrays and to compare them doesn't work properly. Arrays
can't be printed directly by println , nor can they be compared directly using
relational operators such as == . These operations can be done correctly by loop-
ing over the elements of each array and printing/comparing them one at a time.
6. int[] data = {7, -1, 13, 24, 6};
7. public static int max(int[] data) {
int max = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
8. public static double average(int[] a) {
double mean = 0.0;
for (int i = 0; i < a.length; i++) {
mean += a[i];
}
return mean / a.length;
}
9. An array traversal is a sequential processing of each of an array's elements.
Common tasks that use arrays include printing an array, comparing two arrays for
equality, and searching an array for a given value.
10. for (int i = 0; i < data.length; i++) {
System.out.println("element [" + i + "] is " + data[i]);
}
11. public static void printBackwards(int[] list) {
if (list.length == 0) {
System.out.println("[]");
} else {
System.out.print("[" + list[list.length - 1]);
for (int i = list.length - 2; i >= 0; i--) {
System.out.print(", " + list[i]);
}
Search WWH ::




Custom Search