- A student is comparing each pair of names to find matching first letters. Consider the following Java code.
String[] names = {"Ava", "Ben", "Amy"};
int matches = 0;
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].charAt(0) == names[j].charAt(0)) {
matches++;
}
}
}
System.out.println(matches);What is the output of the following nested loop? Answer: 1
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 compare pairs of names in an array to count matching first letters, using j = i + 1 to avoid duplicates. Choice B is correct because it finds one match between 'Ava' and 'Amy', both starting with 'A'. Choice A is incorrect because it might result from missing the match or starting j at i, leading to zero counts. 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.
- Consider the following Java code for scanning quiz scores in a 2D array; identify the error and fix.
int[][] scores = {
{8, 9, 10},
{7, 6, 9}
};
int max = 0;
for (int r = 0; r <= scores.length; r++) {
for (int c = 0; c < scores[r].length; c++) {
if (scores[r][c] > max) max = scores[r][c];
}
}
System.out.println(max); Answer: Change outer condition to r < scores.length
This question tests AP Computer Science A nested iteration, specifically identifying and fixing array bounds errors in nested loops. Nested loops with 2D arrays require careful attention to loop boundaries to avoid ArrayIndexOutOfBoundsException. In this problem, the outer loop uses r <= scores.length, which causes an error because array indices go from 0 to length-1. Choice B is correct because changing to r < scores.length ensures we only access valid indices (0 and 1 for an array of length 2). Choice A would create a different bounds error in the inner loop, while choices C and D don't address the actual problem. To help students: remember that array.length gives the size, but valid indices are 0 through length-1. Always use < with array.length, never <=, to avoid off-by-one errors.
- 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[n];
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? Answer: Runs in O(n2) time as n grows
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. - What is the output of the following nested loop when counting pairs of study partners?
String[] students = {"Ana", "Ben", "Cy"};
int pairs = 0;
for (int i = 0; i < students.length; i++) {
for (int j = i + 1; j < students.length; j++) {
pairs++;
}
}
System.out.println(pairs); Answer: 3
This question tests AP Computer Science A nested iteration, specifically counting unique pairs without repetition. The key insight is that the inner loop starts at i + 1, preventing duplicate pairs and self-pairing. In this problem with 3 students, the loops generate pairs: (0,1)=Ana-Ben, (0,2)=Ana-Cy, and (1,2)=Ben-Cy, totaling 3 unique pairs. Choice C is correct because this pattern counts each pair exactly once without repetition. The formula for combinations is n(n-1)/2, which equals 3(2)/2 = 3 for n=3 students. To help students: trace through with actual indices and notice how j = i + 1 prevents counting (Ben,Ana) separately from (Ana,Ben). This pattern is common for generating combinations without repetition.
- 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[0][0];
for (int r = 0; r < cal.length; r++) {
for (int c = 0; c < cal[r].length; c++) {
if (cal[r][c] > max) max = cal[r][c];
}
}
System.out.print(max);What is the output of the following nested loop? Answer: 650
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.
- A student is scanning a seating chart stored in a 2D array. Consider the following Java code.
int[][] seats = {
{1, 2, 3},
{4, 5, 6}
};
for (int r = 0; r < seats.length; r++) {
for (int c = 0; c <= seats[r].length; c++) {
System.out.print(seats[r][c] + " ");
}
}Identify the error in the nested loop and suggest a fix. Answer: Change inner condition to c < seats[r].length
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 attempt to print all elements of a 2D seating array, but an off-by-one error causes an index out of bounds. Choice A is correct because changing the inner condition to c < seats[r].length prevents accessing beyond the array's length of 3. Choice B is incorrect because adjusting the outer loop to r <= seats.length would add an extra iteration, still causing bounds issues. 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[r].length; c++) {
System.out.print(nums[r][c]);
}
System.out.println();
} Answer: Start c at nums[r].length - 1 and decrement
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 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[0][0];
for (int r = 0; r < steps.length; r++) {
for (int c = 0; c < steps[r].length; c++) {
if (steps[r][c] > max) {
max = steps[r][c];
}
}
}
System.out.println(max);What is the output of the following nested loop? Answer: 6000
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.
- A game board is stored as a 2D char array, and the program prints it row by row. Consider the following Java code.
char[][] board = {
{'X', 'O'},
{'O', 'X'}
};
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[r].length; c++) {
System.out.print(board[r][c]);
}
}What is the output of the following nested loop? Answer: XOOX
This question tests AP Computer Science A nested iteration, specifically understanding output order when printing 2D array elements. Nested loops process elements row-by-row when the outer loop controls rows and the inner loop controls columns, printing elements in sequence without line breaks. In this problem, the loops print board[0][0]='X', board[0][1]='O', board[1][0]='O', board[1][1]='X' consecutively without newlines. Choice A is correct because the elements are printed in row-major order: first row (XO) followed by second row (OX), resulting in XOOX. Choice B incorrectly assumes automatic line breaks between rows, while C and D show incorrect traversal orders. To help students: emphasize that System.out.print() doesn't add line breaks automatically. Draw arrows showing the traversal path through the 2D array to visualize the output sequence.
- 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? Answer: Two lines, each with three (row,col) pairs
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.
- Given the program below, a seating chart is stored in a 2D array; what is printed?
int[][] seats = {
{1, 0, 1},
{1, 1, 0}
};
int filled = 0;
for (int r = 0; r < seats.length; r++) {
for (int c = 0; c < seats[0].length; c++) {
if (seats[r][c] == 1) filled++;
}
}
System.out.println(filled); Answer: 4
This question tests AP Computer Science A nested iteration, specifically understanding how nested loops count elements in a 2D array. Nested iteration involves a loop inside another loop, where the inner loop executes completely for each iteration of the outer loop, allowing us to process every element in a 2D data structure. In this problem, the nested loops iterate through a 2D array representing a seating chart, counting all seats marked with 1 (filled seats). Choice A is correct because the loops visit all 6 positions: (0,0)=1, (0,1)=0, (0,2)=1, (1,0)=1, (1,1)=1, (1,2)=0, finding exactly 4 seats with value 1. Choice B would be incorrect as it overcounts the filled seats. To help students: trace through each iteration step-by-step with row and column indices. Draw the 2D array and mark each position as you visit it to visualize the traversal pattern.
- 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[i].equals(names[j])) pairs++;
}
}
System.out.print(pairs);What is the output of the following nested loop? Answer: 1
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.
- 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();
} Answer: 0,0 0,1 0,2
1,0 1,1 1,2
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.
- Identify the error in the nested loop for printing a 2D map and suggest a fix.
int[][] map = {
{1, 2},
{3, 4},
{5, 6}
};
for (int r = 0; r < map.length; r++) {
for (int c = 0; c < map.length; c++) {
System.out.print(map[r][c] + " ");
}
System.out.println();
} Answer: Change inner loop to c < map[r].length
This question tests AP Computer Science A nested iteration, specifically identifying incorrect loop bounds in 2D array processing. The error occurs because the inner loop uses map.length (which is 3, the number of rows) instead of map[r].length (which is 2, the number of columns per row). In this problem, the inner loop tries to access column index 2, but each row only has indices 0 and 1, causing an ArrayIndexOutOfBoundsException. Choice B is correct because changing to c < map[r].length ensures we only access valid column indices for each row. This is especially important for non-square arrays. To help students: always use array[row].length for column bounds in non-square arrays. Draw the array dimensions to visualize why using the wrong length causes errors.
- A student prints coordinates for seats in a small theater using nested loops. Given the program below,
for (int r = 1; r <= 2; r++) {
for (int c = 1; c <= 3; c++) {
System.out.print("(" + r + "," + c + ")");
}
}What is the output of the following nested loop? Answer: (1,1)(1,2)(1,3)(2,1)(2,2)(2,3)
This question tests AP Computer Science A nested iteration, specifically generating coordinate pairs in row-major order. Nested iteration with explicit loop bounds creates all combinations systematically, with the outer loop controlling the first coordinate and inner loop the second. In this problem, for each row value (1,2), the inner loop generates all column values (1,2,3), producing coordinates in order: (1,1)(1,2)(1,3) for row 1, then (2,1)(2,2)(2,3) for row 2. Choice A is correct because it shows row-major order traversal, completing all columns for row 1 before moving to row 2. Choice B would be column-major order, while C and D show incorrect bounds or reversed order. To help students: visualize as a grid and trace with your finger left-to-right, top-to-bottom. Practice predicting output order before running code.
- 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[pts.length];
for (int r = 0; r < pts.length; r++) {
for (int c = 0; c < pts[r].length; c++) {
totals[r] += pts[r][c];
}
}
System.out.print(totals[0] + "," + totals[1]);What is the output of the following nested loop? Answer: 15,12
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 wants to replace every zero in a grid with -1 for cleanup. Given the program below,
int[][] grid = {
{0, 2},
{3, 0}
};
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == 0) {
grid[r][c] = -1;
}
}
}
System.out.println(grid[0][0] + " " + grid[1][1]);What is the output of the following nested loop? Answer: -1 -1
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 traverse a 2D grid, replacing every zero with -1 and then printing specific modified elements. Choice A is correct because it replaces the zeros at [0][0] and [1][1], outputting '-1 -1'. Choice B is incorrect because it assumes no changes occur, printing the original '0 0'. 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.
- A game uses a 2D char board to count walls ('#') in a level layout. Consider the following Java code.
char[][] board = {
{'#', '.', '#'},
{'.', '.', '#'}
};
int walls = 0;
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[r].length; c++) {
if (board[r][c] == '#') {
walls++;
}
}
}
System.out.println(walls);What is the output of the following nested loop? Answer: 3
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 traverse a 2D char array representing a game board, counting the number of '#' characters for walls. Choice B is correct because it accurately counts the three '#' symbols across the grid, incrementing the counter each time one is found. Choice A is incorrect because it might stem from counting only one row or missing some elements, resulting in an undercount like 2. 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.
- A student models a pixel-art image as a 2D array of ints. Given the program below,
int[][] img = {
{1, 0, 1},
{1, 1, 0}
};
int count = 0;
for (int r = 0; r < img.length; r++) {
for (int c = 0; c < img[r].length; c++) {
if (img[r][c] == 1) count++;
}
}
System.out.print(count);What is the output of the following nested loop? Answer: 4
This question tests AP Computer Science A nested iteration, specifically counting elements that meet a condition in a 2D array. Nested iteration allows systematic traversal of all elements in a two-dimensional structure, with the inner loop completing for each outer loop iteration. In this problem, the nested loops examine each element in the 2x3 array and increment count when the element equals 1: img[0][0]=1, img[0][2]=1, img[1][0]=1, img[1][1]=1. Choice B is correct because exactly 4 elements equal 1, as verified by tracing through all positions. Choice A (3) would miss one occurrence, while C (5) would overcount, and D (2) would significantly undercount. To help students: create a grid visualization and mark each 1 as you trace the loops. Practice predicting the count before running code to strengthen pattern recognition.
- A class analyzes a 2D array of survey ratings and wants the average per row. Consider the following Java code.
int[][] ratings = {
{4, 5, 3},
{2, 1, 3}
};
for (int r = 0; r < ratings.length; r++) {
int rowSum = 0;
for (int c = 0; c < ratings[r].length; c++) {
rowSum += ratings[r][c];
}
System.out.print(rowSum + " ");
}What is the output of the following nested loop? Answer: 12 6
This question tests AP Computer Science A nested iteration, specifically calculating row sums within the loop structure. Nested iteration allows processing each row independently, with the inner loop completing a full row calculation before moving to the next row. In this problem, rowSum resets to 0 for each row, then accumulates that row's values: row 0 gives 4+5+3=12, row 1 gives 2+1+3=6, printing each sum immediately. Choice A is correct because it shows the row sums in order: 12 for the first row and 6 for the second row, with spaces between. Choice B reverses the sums, while C and D show individual elements or incorrect calculations. To help students: emphasize variable scope - rowSum resets for each row because it's declared inside the outer loop. Trace showing how rowSum changes within each row iteration.