Nested Iteration
Help Questions
AP Computer Science A › Nested Iteration
A class stores daily step counts in a 2D array (weeks by days). Given the program below,
int[][] steps = {
{1000, 2000, 3000},
{4000, 5000, 6000}
};
int max = steps<u>0</u><u>0</u>;
for (int r = 0; r < steps.length; r++) {
for (int c = 0; c < steps<u>r</u>.length; c++) {
if (steps<u>r</u><u>c</u> > max) {
max = steps<u>r</u><u>c</u>;
}
}
}
System.out.println(max);
What is the output of the following nested loop?
3000
4000
5000
6000
Explanation
This question tests AP Computer Science A nested iteration, specifically understanding how nested loops function in Java. Nested iteration involves a loop inside another loop, where the inner loop executes completely every time the outer loop executes once. This is used to process multi-dimensional data structures like arrays and matrices. In this problem, the nested loops scan a 2D array of step counts to find the maximum value across all weeks and days. Choice B is correct because it identifies 6000 as the highest value after comparing all elements in the array. Choice A is incorrect because it could result from misidentifying the max as 5000, perhaps by skipping the last element. To help students: Practice tracing loop execution with small data sets. Encourage predicting output before running code to bolster understanding of loop mechanics. Watch for: common errors like off-by-one and incorrect loop nesting.
What change to the nested loop would cause the program to print each row in reverse order?
int[][] nums = {
{1, 2, 3},
{4, 5, 6}
};
for (int r = 0; r < nums.length; r++) {
for (int c = 0; c < nums<u>r</u>.length; c++) {
System.out.print(nums<u>r</u><u>c</u>);
}
System.out.println();
}
Swap r and c in nums[r][c] access
Start r at nums.length - 1 and decrement
Start c at nums[r].length - 1 and decrement
Change condition to c <= nums[r].length
Explanation
This question tests AP Computer Science A nested iteration, specifically modifying loop traversal order. To reverse the order of elements within each row, we need to change how the inner loop iterates through columns. In this problem, the current code prints each row forward (1 2 3, then 4 5 6), but we want reverse order (3 2 1, then 6 5 4). Choice A is correct because starting c at nums[r].length - 1 and decrementing (c--) makes the inner loop traverse columns from right to left. Choice B would reverse row order but not column order within rows. To help students: visualize array traversal direction and remember that decrementing loops require starting at the highest valid index (length - 1) and continuing while >= 0.
A student is printing seats in a small theater grid (rows then columns). Given the program below,
for (int row = 1; row <= 2; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("(" + row + "," + col + ") ");
}
System.out.println();
}
What is the output of the following nested loop?
Three lines, each with two (row,col) pairs
Two lines, each with three (row,col) pairs
One line with six (row,col) pairs
Six lines, each with one (row,col) pair
Explanation
This question tests AP Computer Science A nested iteration, specifically understanding how nested loops function in Java. Nested iteration involves a loop inside another loop, where the inner loop executes completely every time the outer loop executes once. This is used to process multi-dimensional data structures like arrays and matrices. In this problem, the nested loops print seat coordinates in a theater grid, with the outer loop handling rows and the inner loop handling columns, followed by a newline. Choice A is correct because it produces two lines, each with three (row,col) pairs, matching the loop bounds from 1 to 2 rows and 1 to 3 columns. Choice D is incorrect because it would occur without the println statement after the inner loop, resulting in six separate lines instead of grouped rows. To help students: Practice tracing loop execution with small data sets. Encourage predicting output before running code to bolster understanding of loop mechanics. Watch for: common errors like off-by-one and incorrect loop nesting.
Which of the following correctly completes the nested loop to sum all temperatures in a 2D array?
int[][] temps = {
{70, 72, 68},
{65, 66, 64}
};
int sum = 0;
for (int r = 0; r < temps.length; r++) {
for (int c = 0; c < temps<u>r</u>.length; c++) {
// missing line
}
}
System.out.println(sum);
sum += temps[r][c];
sum = temps[r][c];
sum += temps[r][c + 1];
sum += temps[c][r];
Explanation
This question tests AP Computer Science A nested iteration, specifically accumulating values from a 2D array. Nested loops allow us to visit every element in a 2D array and perform operations like summing all values. In this problem, we need to add each temperature value to a running sum variable. Choice C is correct because sum += temps[r][c] properly accumulates each array element using the correct row-column indices. Choice A incorrectly swaps indices, choice B overwrites instead of accumulating, and choice D would cause an array bounds error. To help students: remember that += adds to the existing value while = replaces it. Also, always use the loop variables (r and c) as indices in the same order they appear in the loops.
Given the program below, a list of usernames is checked for shared letters; what is printed?
String[] names = {"ava", "li"};
int matches = 0;
for (int i = 0; i < names.length; i++) {
for (int j = 0; j < names<u>i</u>.length(); j++) {
if (names<u>i</u>.substring(j, j + 1).equals("a")) {
matches++;
}
}
}
System.out.println(matches);
0
1
2
3
Explanation
This question tests AP Computer Science A nested iteration, specifically processing strings within an array using nested loops. The outer loop iterates through array elements (strings), while the inner loop processes each character within those strings. In this problem, the code counts how many times the letter 'a' appears across all names in the array. Choice B is correct because "ava" contains 2 'a's (at positions 0 and 2) and "li" contains 0 'a's, giving a total of 2 matches. The substring method extracts one character at a time for comparison. To help students: trace through each string character by character, and remember that string indices start at 0. Practice using substring(j, j+1) to extract single characters from strings.
A student counts duplicate pairs in a list of usernames to find repeats. Given the program below,
String[] names = {"ava", "ben", "ava", "cy"};
int pairs = 0;
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names<u>i</u>.equals(names<u>j</u>)) pairs++;
}
}
System.out.print(pairs);
What is the output of the following nested loop?
0
1
2
3
Explanation
This question tests AP Computer Science A nested iteration, specifically counting duplicate pairs without double-counting. Nested iteration with j starting at i+1 ensures each pair is checked exactly once, avoiding both self-comparison and duplicate pair counting. In this problem, the loops compare each name with all subsequent names: i=0 compares "ava" with "ben", "ava", and "cy", finding one match at position 2. Choice B is correct because exactly one duplicate pair exists ("ava" at indices 0 and 2). Choice A (0) would mean no duplicates, while C and D would indicate multiple duplicate pairs. To help students: draw a comparison matrix and cross out the diagonal and lower triangle to visualize which comparisons occur. Emphasize why j=i+1 prevents counting the same pair twice.
A teacher wants to compute each student's total points from a 2D array of assignments. Consider the following Java code.
int[][] pts = {
{5, 4, 6},
{3, 7, 2}
};
int[] totals = new int<u>pts.length</u>;
for (int r = 0; r < pts.length; r++) {
for (int c = 0; c < pts<u>r</u>.length; c++) {
totals<u>r</u> += pts<u>r</u><u>c</u>;
}
}
System.out.print(totals<u>0</u> + "," + totals<u>1</u>);
What is the output of the following nested loop?
15,12
5,3
6,7
12,15
Explanation
This question tests AP Computer Science A nested iteration, specifically accumulating row sums into a separate array. Nested iteration can process 2D data while storing results in a 1D array, with the outer loop index determining where to store each row's result. In this problem, totals[0] accumulates row 0's values (5+4+6=15) and totals[1] accumulates row 1's values (3+7+2=12), then both are printed. Choice A is correct because it shows the proper row sums: 15 for the first student and 12 for the second student. Choice B reverses the order, while C and D show individual elements rather than sums. To help students: trace with separate running totals for each row, showing how totals[r] corresponds to row r's sum. Practice identifying which index controls row selection versus column selection.
A student compares two nested-loop versions for checking all pairs of items in an array. Consider the following Java code.
int n = 100;
int[] a = new int<u>n</u>;
int checks = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
checks++;
}
}
System.out.print(checks);
How does the nested iteration in this code affect performance?
Runs in $O(1)$ time regardless of n
Runs in $O(\log n)$ time as n grows
Runs in $O(n)$ time as n grows
Runs in $O(n^2)$ time as n grows
Explanation
This question tests AP Computer Science A nested iteration, specifically analyzing time complexity of nested loops. Nested iteration where both loops run n times results in n² total iterations, as the inner loop executes n times for each of the n outer loop iterations. In this problem, with n=100, the outer loop runs 100 times and for each iteration, the inner loop also runs 100 times, resulting in 100×100=10,000 total checks. Choice B is correct because the number of operations grows quadratically with n - doubling n quadruples the work. Choice A (linear) would only apply to a single loop, C (logarithmic) requires dividing the problem size, and D (constant) means no growth with input size. To help students: create a table showing how checks grow as n increases (n=10→100, n=20→400, n=100→10,000). Emphasize that nested loops multiply their iteration counts.
A cafeteria tracks calories for meals in a 2D array by day and meal. Consider the following Java code.
int[][] cal = {
{400, 500, 600},
{450, 550, 650}
};
int max = cal<u>0</u><u>0</u>;
for (int r = 0; r < cal.length; r++) {
for (int c = 0; c < cal<u>r</u>.length; c++) {
if (cal<u>r</u><u>c</u> > max) max = cal<u>r</u><u>c</u>;
}
}
System.out.print(max);
What is the output of the following nested loop?
450
550
600
650
Explanation
This question tests AP Computer Science A nested iteration, specifically finding the maximum value in a 2D array. Nested iteration enables examination of every element in a two-dimensional structure, updating a tracking variable when conditions are met. In this problem, max starts at 400 and is updated whenever a larger value is found: 500 replaces 400, 600 replaces 500, then 650 replaces 600 as the final maximum. Choice B is correct because 650 is the largest value in the entire array, found at cal[1][2]. Choice A (600) would be the max of only the first row, while C and D represent other non-maximum values. To help students: trace with a table showing current element, current max, and whether max updates. Emphasize checking ALL elements, not stopping early when finding a local maximum.
Consider the following Java code that prints a grid for a pixel-art icon; what is the output?
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
System.out.print(r + "," + c + " ");
}
System.out.println();
}
0,0 0,1 0,2 \n1,0 1,1 1,2
0,0 1,0 0,1 1,1 0,2 1,2
0,0 0,1 \n0,2 1,0 \n1,1 1,2
0,0 0,1 0,2 1,0 1,1 1,2
Explanation
This question tests AP Computer Science A nested iteration, specifically understanding output formatting with nested loops. Nested loops can generate patterns by controlling when to print values versus newlines, creating structured output. In this problem, the outer loop controls rows (0 to 1) and prints a newline after each row completes, while the inner loop prints column coordinates with spaces. Choice B is correct because it shows the proper formatting: first row prints "0,0 0,1 0,2 " then newline, second row prints "1,0 1,1 1,2 " then newline. Choice D lacks the newline characters that separate rows. To help students: trace the execution and note exactly when System.out.print() versus System.out.println() executes. The println() after the inner loop creates the row structure in the output.