AP Computer Science A · Topic 6.4
Developing Algorithms Using Arrays Practice
Part of Array.
Practice questions
47
Sample questions
5 of 47 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
int a = 5, b = 9; int temp = a; a = b; b = temp;What are the values of a and b after?
- Acheck_circle
a=9, b=5
- B
a=5, b=9
- C
a=5, b=5
- D
a=9, b=9
Why
The temp variable preserves a's value while it is overwritten by b.
- A
Sample 2difficulty 1/5
int[] a = {3, 1, 4, 1, 5, 9, 2, 6}; int sum = 0; for (int x : a) sum += x;What is sum?
- A
29
- B
32
- C
30
- Dcheck_circle
31
Why
3+1+4+1+5+9+2+6 = 31.
- A
Sample 3difficulty 2/5
int[] a = {2, 4, 6, 8}; int sum = 0; for (int i = 0; i < a.length - 1; i++) { sum += a[i]; } System.out.println(sum);What is printed?
- Acheck_circle
12
- B
20
- C
18
- D
8
Why
Condition i < a.length - 1 stops at i=2, so a[3]=8 is skipped. Sum is 2+4+6 = 12.
- A
Sample 4difficulty 2/5
int[] a = {3, 1, 4, 1, 5, 9, 2, 6}; int sum = 0; for (int i = 2; i < 5; i++) sum += a[i];What is sum?
- A
9
- B
8
- Ccheck_circle
10
- D
11
Why
a[2]+a[3]+a[4] = 4+1+5 = 10.
- A
Sample 5difficulty 2/5
public static double avg(int[] a) { int total = 0; for (int x : a) total += x; return /* missing */; }Which expression computes the average correctly?
- A
a.length / total
- B
total / (double) a
- Ccheck_circle
(double) total / a.length
- D
total / a.length
Why
Casting total to double forces floating-point division; otherwise integer division would truncate.
- A