Nested Iteration

Help Questions

AP Computer Science A › Nested Iteration

Questions 1 - 10
1

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)(2,1)(1,2)(2,2)(1,3)(2,3)

(1,1)(1,2)(2,1)(2,2)(3,1)(3,2)

(2,1)(2,2)(2,3)(1,1)(1,2)(1,3)

(1,1)(1,2)(1,3)(2,1)(2,2)(2,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.

2

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(n)$ time as n grows

Runs in $O(\log n)$ time as n grows

Runs in $O(n^2)$ time as n grows

Runs in $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.

3

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<u>r</u>.length; c++) {

    System.out.print(board<u>r</u><u>c</u>);

  }

}

What is the output of the following nested loop?

XXOO

OXOX

XOOX

XO OX

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.

4

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.

5

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<u>0</u>.length; c++) {

    sum += temps<u>r</u><u>c</u>;

  }

}

System.out.print(sum);

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

Start c at 1 to avoid index 0

Use c <= temps[0].length for all rows

Change inner bound to temps[r].length

Change outer bound to temps[0].length

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.

6

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?

5,3

15,12

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.

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

8

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<u>r</u>.length; c++) {

    rowSum += ratings<u>r</u><u>c</u>;

  }

  System.out.print(rowSum + " ");

}

What is the output of the following nested loop?

5 3

12 6

6 12

4 2

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.

9

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<u>i</u>.charAt(0) == names<u>j</u>.charAt(0)) {

      matches++;

    }

  }

}

System.out.println(matches);

What is the output of the following nested loop?

0

1

2

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.

10

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<u>r</u>.length; c++) {

    if (grid<u>r</u><u>c</u> == 0) {

      grid<u>r</u><u>c</u> = -1;

    }

  }

}

System.out.println(grid<u>0</u><u>0</u> + " " + grid<u>1</u><u>1</u>);

What is the output of the following nested loop?

0 0

0 -1

-1 0

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

Page 1 of 3