Java Reference
In-Depth Information
Self-Check Problems
Section 7.1: Array Basics
1. What expression should be used to access the first element of an array of integers called numbers ? What expression
should be used to access the last element of numbers , assuming it contains 10 elements? What expression can be
used to access its last element, regardless of its length?
2. Write code that creates an array of integers named data of size 5 with the following contents:
[0]
[1]
[2]
[3]
[4]
data
27
51
33
-1
101
3. Write code that stores all odd numbers between
6 and 38 into an array using a loop. Make the array's size exactly
large enough to store the numbers.
Then, try generalizing your code so that it will work for any minimum and maximum values, not just -6 and 38.
4. What elements does the array numbers contain after the following code is executed?
int[] numbers = new int[8];
numbers[1] = 4;
numbers[4] = 99;
numbers[7] = 2;
int x = numbers[1];
numbers[x] = 44;
numbers[numbers[7]] = 11; // uses numbers[7] as index
5. What is wrong with the following code?
int[] first = new int[2];
first[0] = 3;
first[1] = 7;
int[] second = new int[2];
second[0] = 3;
second[1] = 7;
// print the array elements
System.out.println(first);
System.out.println(second);
// see if the elements are the same
if (first == second) {
System.out.println("They contain the same elements.");
} else {
System.out.println("The elements are different.");
}
 
 
Search WWH ::




Custom Search