Lecture 9 Arrays I
Lecture 9 Arrays I
Computer Programming
Lecture 9: Arrays I
Can we solve this problem?
• Consider the following program (input underlined):
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Array declaration, cont.
• The length can be entered by the user
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Array declaration, cont.
• The length can be any integer expression.
int x = 2 * 3 + 1;
int[] data = new int[x % 5 + 2];
• Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[9]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[10]); // exception
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Accessing array elements
int[] numbers = new int[8];
numbers[1] = 3;
numbers[4] = 99;
numbers[6] = 2;
int x = numbers[1];
numbers[x] = 42;
numbers[numbers[6]] = 11; // use numbers[6] as
index
x 3
index 0 1 2 3 4 5 6 7
numbers value 0 3 11 42 99 0 2 0
Arrays and for loops
• It is common to use for loops to access array
elements.
for (int i = 0; i < 8; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println(); // output: 0 3 11 42 99 0 2 0
index 0 1 2 3 4 5 6
value 12 49 -2 26 5 17 -6
7
5
11
Array traversal (Example)
// Find the smallest element in an array.
public class Smallest {
public static void main(String[] args) {
int[] num = {12, 49, -5, 26, -2, 17, 6}; // array
initialization
int min = num[0];
int minIndex = 0;
for (int i = 1; i < num.length; i++) {
if (num[i] < min) {
min = num[i];
minIndex = i;
}
}
// report results
System.out.println(“The smallest element is: “ + min);
System.out.println(“The index of the smallest element is:
“ + minIndex);
}
}
"Array mystery" problem
• What element values are stored in the following
array?
Output:
e is [0, 14, 4, 6, 8]
// report results
System.out.println("Average temp =“+ average);
System.out.println(count + " days above average");