---
title: "2D Array Algorithms | FiveStudy"
description: "Grid versions of the workhorses, row/column slices as single loops, and in-place transforms."
url: https://fivestudy.com/guides/2d-array-algorithms
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# 2D Array Algorithms

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Data Collections

AP® Computer Science A · Data Collections

# Implementing *2D Array* Algorithms

Standard algorithms on 2D arrays, for the whole grid or a designated row, column, or subsection: minimums, maximums, sums, and averages; property checks and counts; consecutive pairs and duplicates; and shifting, rotating, and reversing within a row or column.

1. Whole-Grid Results 2. Rows, Columns, Subsections 3. Checking Properties 4. Pairs and Duplicates 5. Shifting and Rotating 6. Reversing

Big Picture

There are standard algorithms that utilize 2D array traversals to determine a minimum or maximum value, compute a sum or average, determine if at least one element or all elements have a particular property, and count the elements having a property, each for the entire 2D array or for a designated row, column, or other subsection. Other standard algorithms access all consecutive pairs of elements, determine the presence or absence of duplicate elements, shift or rotate elements in a row left or right or in a column up or down, and reverse the order of the elements in a row or column.

## 1 Results for the Whole Grid

Every 1D algorithm has a 2D version that runs inside nested loops. To determine a minimum or maximum value of all the elements, start from an actual element, `g[0][0]`, and compare every element with the best so far. Recording the row and column whenever the best changes also gives the location of the minimum or maximum, which is often what a program needs.

To compute a sum or average of all the elements, add every element in a full traversal. The number of elements is the number of rows times the number of columns, `g.length * g[0].length`. Divide as a `double`, by casting the sum or the count, so that the average keeps its fractional part.

Worked Example 1 Whole grid

### Maximum, Its Location, and the Average

Predict the output.

Code

```
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };

int max = sales[0][0];
int maxRow = 0;
int maxCol = 0;
int sum = 0;
for (int r = 0; r < sales.length; r++)
{
    for (int c = 0; c < sales[0].length; c++)
    {
        sum += sales[r][c];
        if (sales[r][c] > max)
        {
            max = sales[r][c];
            maxRow = r;
            maxCol = c;
        }
    }
}
int count = sales.length * sales[0].length;
System.out.println("max " + max + " at [" + maxRow + "][" + maxCol + "]");
System.out.println((double) sum / count);
```

Output

```
max 15 at [1][0]
10.0
```

1. 1 **Start from a real element:** `sales[0][0]`.
2. 2 **Record the location** along with the value whenever a larger element appears.
3. 3 **Average.** The 9 elements sum to 90; casting to `double` before dividing gives 10.0.

**Result:** The output is max 15 at [1][0], then 10.0. A full row-major traversal computes the maximum, its position, and the average of all elements.

Common Mistake 1 · Integer Division in an Average

`sum / count` with two `int` values truncates the result. Write `(double) sum / count` so that the division is done with `double` values.

## 2 Designated Rows, Columns, and Subsections

Each of these algorithms can also be applied to a designated row, column, or other subsection. For a row, fix the row index and loop over the columns; because a row is a 1D array, an enhanced `for` loop over `g[r]` also works. For a column, fix the column index and loop over the rows. Repeating the row computation for every row gives a list of row totals; repeating the column computation gives column totals.

A subsection, such as a rectangle of rows `r1` to `r2` and columns `c1` to `c2`, uses nested loops whose bounds are the edges of the region instead of the edges of the grid. The body of the loop does not change; only the starting and stopping values do. Every bound must stay inside the grid, or the traversal throws an `ArrayIndexOutOfBoundsException`.

**Figure 1.** Sums, averages, minimums, and maximums can be computed for the whole 2D array or for a designated row or column.

| Scope | Loop structure |
| --- | --- |
| Whole 2D array | Nested loops over every row and column (or nested enhanced for) |
| Designated row r | One loop over the columns: `g[r][c]`, or an enhanced for over `g[r]` |
| Designated column c | One loop over the rows: `g[r][c]` with c fixed |
| Subsection | Nested loops starting and stopping at the subsection's row and column bounds |

Worked Example 2 Designated row or column

### Row Sums and a Column Average

Two methods each traverse a single row or column.

Code

```
public static int rowSum(int[][] g, int r)
{
    int sum = 0;
    for (int v : g[r])
    {
        sum += v;
    }
    return sum;
}

public static double colAverage(int[][] g, int c)
{
    int sum = 0;
    for (int r = 0; r < g.length; r++)
    {
        sum += g[r][c];
    }
    return (double) sum / g.length;
}
```

Output

```
row 0: 28
row 1: 30
row 2: 32
8.0
```

1. 1 **A row is a 1D array**, so `rowSum` uses an enhanced for loop over `g[r]`.
2. 2 **A column needs an index loop:** fix `c` and vary `r`. Column 1 holds 7, 4, 13: 24 / 3 = 8.0.

**Result:** The output lists row sums 28, 30, and 32, then 8.0. Results for a designated row or column use one loop with the other index fixed (Figure 1).

**Figure 2.** An algorithm can be restricted to a designated subsection by starting and stopping each loop at the subsection's edges.

Worked Example 3 Subsections

### Summing a Rectangular Region

Sum the elements from row `r1` to `r2` and column `c1` to `c2`, inclusive.

Code

```
public static int regionSum(int[][] g, int r1, int c1, int r2, int c2)
{
    int sum = 0;
    for (int r = r1; r <= r2; r++)
    {
        for (int c = c1; c <= c2; c++)
        {
            sum += g[r][c];
        }
    }
    return sum;
}
```

Output

```
31
32
```

1. 1 **Rows 0 to 1, columns 1 to 2:** 7 + 9 + 4 + 11 = 31.
2. 2 **A single row is also a region:** row 2, columns 0 to 2, sums to 32.
3. 3 **Inclusive bounds** use `<=`; the caller must pass indices inside the grid.

**Result:** The output is 31 and 32. Restricting the loop bounds applies any algorithm to a designated subsection (Figure 2).

Common Mistake 2 · Mixing Inclusive and Exclusive Bounds

When a subsection is described as "rows 1 to 2, inclusive", the loop condition is `r <= 2`; when it is described by a starting index and a number of rows, the condition is `r < start + count`. Decide which description is being used before writing the loop, and check the last index the loop reaches.

## 3 Checking Properties

Determining if at least one element has a particular property, in the entire 2D array or a designated part, returns `true` as soon as one matching element is found and `false` only after the traversal ends. Determining if all elements have a property does the opposite: return `false` at the first failure and `true` after the traversal. Counting the elements with a property adds 1 for every match and never stops early.

Writing each check as a method with parameters, such as the grid, a row or column index, and a limit, makes the code reusable for every row or column and keeps the early `return` statements clear.

Worked Example 4 Properties

### Any, All, and How Many

Predict the output.

Code

```
public static int countOver(int[][] g, int limit)
{
    int count = 0;
    for (int[] row : g)
    {
        for (int v : row)
        {
            if (v > limit)
            {
                count++;
            }
        }
    }
    return count;
}

public static boolean anyBelowInColumn(int[][] g, int c, int limit)
{
    for (int r = 0; r < g.length; r++)
    {
        if (g[r][c] < limit)
        {
            return true;
        }
    }
    return false;
}

public static boolean allAtLeastInRow(int[][] g, int r, int min)
{
    for (int v : g[r])
    {
        if (v < min)
        {
            return false;
        }
    }
    return true;
}
```

Output

```
5
true
true
```

1. 1 **Count in the whole grid.** 12, 15, 11, 13, and 11 exceed 10: 5.
2. 2 **At least one in a column.** Column 1 contains 4, which is below 5: `true` as soon as it is found.
3. 3 **All in a row.** Row 2 is 8, 13, 11, all at least 8: `true` only after checking every element.

**Result:** The output is 5, true, and true. Property checks work on the whole 2D array or on a designated row, column, or subsection.

## 4 Consecutive Pairs and Duplicates

Accessing all consecutive pairs of elements in a 2D array usually means neighbors along a row, `g[r][c]` and `g[r][c + 1]`, or down a column, `g[r][c]` and `g[r + 1][c]`. The index that moves stops one before its last value so that the neighbor exists. Pair algorithms count rises and falls, check whether rows are in order, or find the largest difference between neighbors.

Determining the presence or absence of duplicate elements compares elements with one another. For a single row or column, nested loops with the inner index starting one past the outer index work exactly as for a 1D array. For the whole grid, a helper method that counts how many times a value occurs keeps the code readable: any value whose count is greater than 1 is a duplicate.

Worked Example 5 Consecutive pairs

### Rises Within Each Row

Count how many times a value is larger than the one to its left.

Code

```
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };

int rises = 0;
for (int r = 0; r < sales.length; r++)
{
    for (int c = 0; c < sales[0].length - 1; c++)
    {
        if (sales[r][c + 1] > sales[r][c])
        {
            rises++;
        }
    }
}
System.out.println(rises);
```

Output

```
3
```

1. 1 **Inner bound.** `c < sales[0].length - 1` so that `c + 1` is always a valid column.
2. 2 **Pairs.** Row 0: 7→9 rises. Row 1: 4→11 rises. Row 2: 8→13 rises. The other pairs fall.

**Result:** The output is 3. Consecutive pairs in a 2D array compare neighbors along a row (or down a column), stopping one element early.

Worked Example 6 Duplicates

### Does Any Value Appear Twice?

A helper counts occurrences; a value that occurs more than once is a duplicate.

Code

```
public static int countOf(int[][] g, int target)
{
    int count = 0;
    for (int[] row : g)
    {
        for (int v : row)
        {
            if (v == target)
            {
                count++;
            }
        }
    }
    return count;
}

public static boolean hasDuplicate(int[][] g)
{
    for (int[] row : g)
    {
        for (int v : row)
        {
            if (countOf(g, v) > 1)
            {
                return true;
            }
        }
    }
    return false;
}
```

Output

```
true
2
```

1. 1 **Every element counts itself once**, so a count greater than 1 means another element holds the same value.
2. 2 **11 appears twice** (row 1 and row 2), so `hasDuplicate` returns `true`.

**Result:** The output is true and 2. Determining the presence or absence of duplicates in a 2D array compares each element against the others, here through a helper method.

## 5 Shifting and Rotating in a Row or Column

Shifting moves elements in a row left or right, or in a column up or down, by one position. A rotation also wraps the element that falls off one end around to the other end; a plain shift instead fills the vacated position with a placeholder. Because arrays cannot grow, both operations copy values from cell to cell, and the order of copying matters.

To shift right, copy from the end toward the beginning, so that each value is read before its cell is overwritten; to shift left or up, copy from the beginning. For a rotation, save the element that would be lost in a temporary variable before the copying starts, then store it in the vacated position at the end.

**Figure 3.** Rotating a row right saves the last element, shifts the others right starting from the end, and puts the saved element at index 0.

| Step | Statement | Row 0 afterward |
| --- | --- | --- |
| start |  | 12 7 9 |
| 1 | last = row[2] | 12 7 9 (last = 9) |
| 2 | row[2] = row[1] | 12 7 7 |
| 3 | row[1] = row[0] | 12 12 7 |
| 4 | row[0] = last | 9 12 7 |

Worked Example 7 Rotating a row

### Right by One, From the End

Rotate row 0 one place to the right (Figure 3).

Code

```
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };

int[] row = sales[0];
int last = row[row.length - 1];
for (int c = row.length - 1; c > 0; c--)
{
    row[c] = row[c - 1];
}
row[0] = last;
System.out.println(sales[0][0] + " " + sales[0][1] + " " + sales[0][2]);
```

Output

```
9 12 7
```

1. 1 **`row` refers to `sales[0]`**, so changes through `row` change the 2D array.
2. 2 **Save the last element** before it is overwritten.
3. 3 **Shift from the end backward**, so each value is copied before its cell is reused; then store `last` at index 0.

**Result:** The output is 9 12 7. Rotating a row right saves the last element, shifts the rest right starting from the end, and wraps the saved element to the front.

Worked Example 8 Shifting a column

### Moving Values Up and Filling the Gap

Shift column 2 up by one without wrapping; the bottom becomes 0.

Code

```
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };

int c = 2;
for (int r = 0; r < sales.length - 1; r++)
{
    sales[r][c] = sales[r + 1][c];
}
sales[sales.length - 1][c] = 0;
System.out.println(sales[0][c] + " " + sales[1][c] + " " + sales[2][c]);
```

Output

```
11 11 0
```

1. 1 **Shifting up** copies each element from the row below, working from the top down, so nothing is overwritten before it is copied.
2. 2 **The vacated bottom cell** receives a placeholder, 0, since a shift without wrapping drops the top value.

**Result:** The output is 11 11 0. The direction of a shift decides the direction of the loop: shifting up runs from the top, shifting right runs from the end.

Common Mistake 3 · Shifting Right From the Left End

A loop that copies `row[c + 1] = row[c]` starting at `c = 0` copies the first value into every cell, because each cell is overwritten before its value is moved. Shift right by starting at the end and moving backward.

## 6 Reversing a Row or Column

Reversing the order of the elements in a row or column swaps pairs from both ends toward the middle, using a temporary variable for each swap. For a column, only the row index changes: element `i` swaps with element `g.length - 1 - i`, for `i` less than `g.length / 2`. In a row or column of odd length, the middle element stays in place.

Stopping at the halfway point is essential. A loop that runs over the whole column swaps each pair twice and leaves the column exactly as it started, a bug that is easy to miss because the code produces no error.

**Figure 4.** Reversing the elements of a column swaps pairs from the top and bottom toward the middle; only the row index changes.

Worked Example 9 Reversing a column

### Swapping Top and Bottom

Reverse column 0 (Figure 4).

Code

```
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };

int c = 0;
for (int i = 0; i < sales.length / 2; i++)
{
    int j = sales.length - 1 - i;
    int temp = sales[i][c];
    sales[i][c] = sales[j][c];
    sales[j][c] = temp;
}
for (int r = 0; r < sales.length; r++)
{
    System.out.println(sales[r][c]);
}
```

Output

```
8
15
12
```

1. 1 **Only the row index changes**; the column stays at `c`.
2. 2 **`sales.length / 2`** is 1, so one swap happens: rows 0 and 2.

**Result:** The output is 8, 15, and 12. Reversing a column swaps elements from the top and bottom toward the middle.

| Algorithm | 2D approach |
| --- | --- |
| Minimum or maximum | Start at `g[0][0]` (or the first element of the row/column); compare every element |
| Sum or average | Add elements; divide by the number of elements as a `double` |
| At least one / all / how many | Return early for a match (any) or a failure (all); count otherwise |
| Consecutive pairs | Compare `g[r][c]` with `g[r][c + 1]` (or `g[r + 1][c]`) |
| Duplicates | Compare each element with the others, for example by counting occurrences |
| Shift or rotate a row or column | Save the element that would be lost; copy in the safe direction |
| Reverse a row or column | Swap pairs from both ends toward the middle |

Common Mistake 4 · Reversing Past the Middle

If the swap loop runs to the end of the row or column instead of the middle, every pair is swapped back and the data ends up unchanged. Bound the loop by half the length.

### Four Habits for 2D Algorithms

#### 1. Name the Scope

Whole grid, row, column, or subsection.

#### 2. Fix One Index

For a single row or column.

#### 3. Copy in the Safe Direction

Save what would be lost first.

#### 4. Stop at the Middle

When reversing by swaps.

Core Synthesis

There are standard algorithms that utilize 2D array traversals to determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection; compute a sum or average of all the elements or for a designated row, column, or other subsection; determine if at least one element has a particular property in the entire 2D array or a designated part; determine if all elements of the 2D array or a designated part have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements in the 2D array or a designated part; shift or rotate elements in a row left or right or in a column up or down; and reverse the order of the elements in a row or column.

FiveStudy AP® Computer Science A Study Guide · Data Collections · Implementing 2D Array Algorithms Back to top ↑
