Skip to the content.

Unit 6 Notes

Unit 6: Arrays – AP Computer Science A

🔑 Key Concepts

  • Declaring and initializing arrays
  • Accessing and modifying elements
  • Iterating over arrays using for and enhanced for loops
  • Common array algorithms: sum, max, min, average, count
  • Array bounds and ArrayIndexOutOfBoundsException

📦 Declaring and Initializing Arrays

int[] nums = new int[5]; // [0, 0, 0, 0, 0]
int[] scores = {90, 80, 70}; // [90, 80, 70]

🧪 Accessing and Modifying Elements

scores[1] = 85;
System.out.println(scores[1]); // 85

🔁 Iterating Over Arrays

Traditional for loop:

for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

Enhanced for loop:

for (int score : scores) {
    System.out.println(score);
}

Note: Enhanced for-loops can’t modify array elements.


🔄 Common Array Algorithms

Sum:

int sum = 0;
for (int num : nums) sum += num;

Max:

int max = nums[0];
for (int num : nums) {
    if (num > max) max = num;
}

Average:

double avg = (double) sum / nums.length;

Count elements satisfying a condition:

int count = 0;
for (int n : nums) {
    if (n > 50) count++;
}

⚠️ Out-of-Bounds Errors

Accessing an invalid index causes an exception:

int[] arr = {1, 2, 3};
System.out.println(arr[3]); // ❌ ArrayIndexOutOfBoundsException

🧪 Practice Multiple Choice (5 Questions)

1. What is printed by this code?

int[] arr = {10, 20, 30};
System.out.println(arr[1]);

(A) 10
(B) 20
(C) 30
(D) 1
Answer: (B)


2. What will happen if you access arr[3] in a 3-element array?
(A) Returns 0
(B) Returns null
(C) Throws an exception
(D) Prints nothing
Answer: (C)


3. Which loop correctly sums the elements in an array?

int sum = 0;
for (int i = 0; i < arr.length; i++) {
    sum += arr[i];
}

(A) Yes
(B) No, use i <= arr.length
(C) Only works if values are even
(D) You must use a while loop
Answer: (A)


4. What is the output?

int[] nums = {5, 10, 15};
for (int n : nums) {
    System.out.print(n + " ");
}

(A) 5 10 15
(B) 10 15 5
(C) 15 10 5
(D) Error
Answer: (A)


5. Which of the following correctly counts how many numbers are positive in an array?

int count = 0;
for (int n : nums) {
    if (n > 0) count++;
}

(A) Yes
(B) No, must use .length()
(C) Only works if all values are positive
(D) Fails for empty array
Answer: (A)