AP Computer Science a Quiz: Nested Iteration
20 questions · exam conditions
0:00
Nested IterationQuestion 1 of 20

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?

3
4
5
2
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Nested Iteration

Practice Nested Iteration in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Nested Iteration, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

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?

  1. 3
  2. 4 (correct answer)
  3. 5
  4. 2

Explanation: 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.

Question 2

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?

  1. 5000
  2. 6000 (correct answer)
  3. 4000
  4. 3000

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.

Question 3

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();
}
  1. Start c at nums[r].length - 1 and decrement (correct answer)
  2. Start r at nums.length - 1 and decrement
  3. Change condition to c <= nums[r].length
  4. Swap r and c in nums[r][c] access

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.

Question 4

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?

  1. Two lines, each with three (row,col) pairs (correct answer)
  2. Three lines, each with two (row,col) pairs
  3. One line with six (row,col) pairs
  4. 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.

Question 5

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[r].length; c++) {
    // missing line
  }
}
System.out.println(sum);
  1. sum += temps[c][r];
  2. sum = temps[r][c];
  3. sum += temps[r][c]; (correct answer)
  4. sum += temps[r][c + 1];

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.

Question 6

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[i].length(); j++) {
    if (names[i].substring(j, j + 1).equals("a")) {
      matches++;
    }
  }
}
System.out.println(matches);
  1. 1
  2. 2 (correct answer)
  3. 3
  4. 0

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.

Question 7

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?

  1. 0
  2. 1 (correct answer)
  3. 2
  4. 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.

Question 8

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?

  1. 15,12 (correct answer)
  2. 12,15
  3. 5,3
  4. 6,7

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.

Question 9

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?

  1. Runs in O(n)O(n) time as n grows
  2. Runs in O(n2)O(n^2) time as n grows (correct answer)
  3. Runs in O(logn)O(\log n) time as n grows
  4. Runs in O(1)O(1) time regardless of n

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.

Question 10

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?

  1. 600
  2. 650 (correct answer)
  3. 550
  4. 450

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.

Question 11

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();
}
  1. 0,0 1,0 0,1 1,1 0,2 1,2
  2. 0,0 0,1 0,2 \n1,0 1,1 1,2 (correct answer)
  3. 0,0 0,1 \n0,2 1,0 \n1,1 1,2
  4. 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.

Question 12

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);
  1. 4 (correct answer)
  2. 5
  3. 3
  4. 2

Explanation: 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.

Question 13

How does the nested iteration in this code affect performance when processing a n×nn\times n image grid?

int count = 0;
for (int r = 0; r < n; r++) {
  for (int c = 0; c < n; c++) {
    count++;
  }
}
  1. It runs in O(n)O(n) time overall
  2. It runs in O(n2)O(n^2) time overall (correct answer)
  3. It runs in O(2n)O(2n) time overall
  4. It runs in O(logn)O(\log n) time overall

Explanation: This question tests AP Computer Science A nested iteration, specifically analyzing time complexity of nested loops. When loops are nested, the total iterations multiply: the inner loop runs completely for each iteration of the outer loop. In this problem, both loops run n times, so the inner loop executes n times for each of the n outer iterations, resulting in n×n = n² total operations. Choice B is correct because O(n²) represents quadratic time complexity, which occurs when processing every element in an n×n grid. Choice A would only be true for a single loop, not nested loops. To help students: count total iterations by multiplying loop ranges. For square grids, nested loops touching every element always result in O(n²) complexity.

Question 14

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?

  1. (1,1)(1,2)(1,3)(2,1)(2,2)(2,3) (correct answer)
  2. (1,1)(2,1)(1,2)(2,2)(1,3)(2,3)
  3. (1,1)(1,2)(2,1)(2,2)(3,1)(3,2)
  4. (2,1)(2,2)(2,3)(1,1)(1,2)(1,3)

Explanation: 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.

Question 15

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?

  1. XOOX (correct answer)
  2. XO OX
  3. XXOO
  4. OXOX

Explanation: 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.

Question 16

A student stores weekly temperatures in a 2D array, but the code crashes on some inputs. Given the program below,

int[][] temps = {
  {70, 72, 68},
  {65, 66}
};
int sum = 0;
for (int r = 0; r < temps.length; r++) {
  for (int c = 0; c < temps[0].length; c++) {
    sum += temps[r][c];
  }
}
System.out.print(sum);

Identify the error in the nested loop and suggest a fix.

  1. Change inner bound to temps[r].length (correct answer)
  2. Change outer bound to temps[0].length
  3. Start c at 1 to avoid index 0
  4. Use c <= temps[0].length for all rows

Explanation: This question tests AP Computer Science A nested iteration, specifically identifying and fixing array bounds errors with jagged arrays. Nested iteration can fail when assuming all rows have the same length, causing ArrayIndexOutOfBoundsException when accessing non-existent elements. In this problem, the inner loop uses temps[0].length (which is 3) for all rows, but row 1 only has 2 elements, causing an error when trying to access temps[1][2]. Choice A is correct because changing the inner bound to temps[r].length ensures each row uses its own length, preventing out-of-bounds access. Choice B would change loop structure incorrectly, C would skip valid data, and D would still cause bounds errors. To help students: always use the current row's length for inner loop bounds with potentially jagged arrays. Draw the array structure to visualize different row lengths.

Question 17

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?

  1. 12 6 (correct answer)
  2. 6 12
  3. 4 2
  4. 5 3

Explanation: 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.

Question 18

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?

  1. 0
  2. 1 (correct answer)
  3. 2
  4. 3

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 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.

Question 19

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?

  1. -1 -1 (correct answer)
  2. 0 0
  3. -1 0
  4. 0 -1

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 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.

Question 20

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.

  1. Change inner condition to c < seats[r].length (correct answer)
  2. Change outer condition to r <= seats.length
  3. Initialize c to 1 instead of 0
  4. Increment r inside inner loop instead of c

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 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.