Back

Activity 5.5 — Two-Dimensional Arrays (2D Arrays)

divider

Introduction

Activity 5.5

Two-Dimensional Arrays

What is a 2D array?

  • A 2D array is an array of arrays.
  • It looks like a grid (rows and columns).
  • Use it when data naturally fits a table.
// A 2D array is an "array of arrays"
int[][] grid =
{
{3, 5, 7},
{1, 4, 9},
{8, 6, 2}
};
// Think: grid[row][col]

Vocabulary (Grid Thinking)

  • Row = which inner array
  • Column = which position inside the row
  • grid[row][col] accesses one element

Picture the Grid

For this array:

3 5 7
1 4 9
8 6 2
  • grid[0][0] = 3 (top-left)
  • grid[1][2] = 9 (row 1, col 2)
  • grid[2][1] = 6 (row 2, col 1)

Accessing One Element

Pick a row, then pick a column.

// Accessing one element
int value = grid[2][1]; // row 2, col 1
// value is 6
  • Row index comes first.
  • Column index comes second.

Two different lengths

  • grid.length = number of rows
  • grid[r].length = number of columns in row r
  • This prevents the #1 2D array bug.
// Common bug: mixing up row and col
// grid.length is # of rows
// grid[r].length is # of columns in row r

Traversal Step 1: One Row

Before scanning a whole grid, practice one row.

// Row traversal (one row)
for (int c = 0; c < grid[0].length; c++)
{
System.out.println(grid[0][c]);
}

Traversal Step 2: Whole Grid

You need a loop for rows and a loop for columns.

// Full grid traversal (nested loops)
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
System.out.println("grid[" + r + "][" + c + "] = " + grid[r][c]);
}
}
  • Outer loop controls the row
  • Inner loop controls the column

Printing the Grid Nicely

Row by row, with spaces between columns.

// Printing a grid as rows
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
System.out.print(grid[r][c] + " ");
}
System.out.println();
}

Algorithms on Grids

  • Sum all values (accumulator)
  • Count matches (if + counter)
  • Find max/min (best-so-far)
  • Row totals (reset sum each row)

Row Total Pattern

Reset the sum for each new row.

// Row sum pattern
int rowSum = 0;
for (int c = 0; c < grid[r].length; c++)
{
rowSum += grid[r][c];
}

Find a Max in a Grid

Same idea as 1D, but inside nested loops.

// Finding a max value in a 2D array
int max = grid[0][0];
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
if (grid[r][c] > max)
{
max = grid[r][c];
}
}
}

Practical Uses

  • Gradebook (students × assignments)
  • Steps tracker (people × days)
  • Seating chart (rows × seats)
  • Game boards (later)

Today's Work

  • Start simple: access + print
  • Move to algorithms: sum, max, count
  • Finish with mini apps: gradebook + seat map

'F' → Fullscreen

Objectives

  • icon Explain how a 2D array represents rows and columns.
  • icon Access and update values using grid[row][col].
  • icon Traverse a 2D array using nested for loops (row-major order).
  • icon Apply common algorithms (sum, max, counting, row totals) to a grid.
divider

Activity Tasks

  • icon Create a new project named Activity5-5-2DArrays.
  • icon Complete Tasks 1-4. Tasks 5-6 are “mini apps” for extra practice.
  • icon Keep your loops correct: rows use grid.length, columns use grid[r].length.

Figures: Examples

Figure 1 — A 3x3 Grid
// Figure 1 — A small 2D array you can picture as a grid
int[][] grid =
{
{3, 5, 7},
{1, 4, 9},
{8, 6, 2}
};
// grid has 3 rows and 3 columns
// grid[0][0] is 3
// grid[1][2] is 9
// grid[2][1] is 6
Figure 2 — Access + Update
// Figure 2 — Access + update one element
int[][] seats =
{
{0, 0, 1, 0},
{0, 1, 1, 0},
{0, 0, 0, 0}
};
// 1 means occupied, 0 means empty
System.out.println(seats[1][1]); // prints 1
// Mark row 2, col 0 as occupied
seats[2][0] = 1;
Figure 3 — Nested Loop Template
// Figure 3 — Nested loop traversal template (Allman braces)
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
// use grid[r][c]
}
}

Task 1: Grid Basics (Access + Update)

  • icon Practice reading and changing a single element.
  • icon This builds confidence before nested loops.
Task 1 — Access + Update
public class Program
{
public static void main(String[] args)
{
// Task 1 — Grid Basics (Access + Update)
//
// You are given a 3x3 grid of integers.
// 1) Print the center element (row 1, col 1)
// 2) Print the top-right element (row 0, col 2)
// 3) Change the bottom-left element (row 2, col 0) to 99
// 4) Print the updated bottom-left element to confirm
int[][] grid =
{
{3, 5, 7},
{1, 4, 9},
{8, 6, 2}
};
System.out.println("Center (1,1): " + grid[1][1]);
System.out.println("Top-right (0,2): " + grid[0][2]);
grid[2][0] = 99;
System.out.println("Updated bottom-left (2,0): " + grid[2][0]);
}
}

Task 2: Print the Grid Nicely

  • icon Use nested loops to print the grid as rows and columns.
  • icon You should see a clean 3x3 table.
Task 2 — Print Grid
public class Program
{
public static void main(String[] args)
{
// Task 2 — Print the Grid Nicely
//
// Print the grid so it looks like rows and columns.
// Example:
// 3 5 7
// 1 4 9
// 8 6 2
int[][] grid =
{
{3, 5, 7},
{1, 4, 9},
{8, 6, 2}
};
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
System.out.print(grid[r][c] + " ");
}
System.out.println();
}
}
}

Task 3: Grid Stats (Sum, Max, Count)

  • icon Compute the sum of all values.
  • icon Find the max value in the grid.
  • icon Count how many values are even.
Task 3 — Grid Algorithms
public class Program
{
public static void main(String[] args)
{
// Task 3 — Grid Stats (Sum, Max, Count)
//
// Using traversal:
// 1) Compute the sum of ALL values in the grid
// 2) Find the maximum value
// 3) Count how many values are even
int[][] grid =
{
{3, 5, 7},
{1, 4, 9},
{8, 6, 2}
};
int sum = 0;
int max = grid[0][0];
int evenCount = 0;
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[r].length; c++)
{
int value = grid[r][c];
sum += value;
if (value > max)
{
max = value;
}
if (value % 2 == 0)
{
evenCount++;
}
}
}
System.out.println("Sum: " + sum);
System.out.println("Max: " + max);
System.out.println("Even count: " + evenCount);
}
}

Task 4: Row Totals (Weekly Steps)

  • icon Sum each row separately and print a weekly total per person.
  • icon Track the person with the highest total.
Task 4 — Row Totals
public class Program
{
public static void main(String[] args)
{
// Task 4 — Row Totals (Practical: Weekly Steps)
//
// Each row is a person.
// Each column is a day of the week (Mon-Sun).
//
// 1) Print each person's total steps for the week.
// 2) Print which person (row index) had the highest weekly total.
int[][] steps =
{
{5200, 6100, 4300, 7000, 8000, 12000, 9000}, // Person 0
{8000, 7800, 8200, 7900, 8100, 8300, 7600}, // Person 1
{3000, 4500, 5000, 4000, 6500, 7000, 6000} // Person 2
};
int bestPerson = 0;
int bestTotal = 0;
for (int r = 0; r < steps.length; r++)
{
int rowSum = 0;
for (int c = 0; c < steps[r].length; c++)
{
rowSum += steps[r][c];
}
System.out.println("Person " + r + " weekly total: " + rowSum);
if (r == 0 || rowSum > bestTotal)
{
bestTotal = rowSum;
bestPerson = r;
}
}
System.out.println("Highest weekly total: Person " + bestPerson);
System.out.println("Total steps: " + bestTotal);
}
}

Task 5: Gradebook Mini App

  • icon Compute each student's average (row = student).
  • icon Let the user select a student and print their scores.
Task 5 — Gradebook
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
// Task 5 — Gradebook Mini App (Practical)
//
// Rows = students
// Cols = assignments
//
// 1) Print each student's average.
// 2) Ask the user for a student number (0-2) and print that student's scores.
//
// NOTE: We'll keep it small so it's easy to trace.
int[][] grades =
{
{90, 82, 88, 100}, // Student 0
{70, 85, 79, 92}, // Student 1
{95, 91, 93, 89} // Student 2
};
// 1) Student averages
for (int r = 0; r < grades.length; r++)
{
int sum = 0;
for (int c = 0; c < grades[r].length; c++)
{
sum += grades[r][c];
}
double avg = (double) sum / grades[r].length;
System.out.println("Student " + r + " average: " + avg);
}
// 2) Lookup a student row and print their scores
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a student number (0-2): ");
int student = scanner.nextInt();
if (student < 0 || student >= grades.length)
{
System.out.println("Invalid student number.");
}
else
{
System.out.print("Student " + student + " scores: ");
for (int c = 0; c < grades[student].length; c++)
{
System.out.print(grades[student][c] + " ");
}
System.out.println();
}
scanner.close();
}
}

Task 6: Seat Map Scanner

  • icon Count occupied and empty seats.
  • icon Print coordinates of all occupied seats.
  • icon This is a classic “scan a grid” pattern.
Task 6 — Seat Map
public class Program
{
public static void main(String[] args)
{
// Task 6 — Seat Map (Practical + Visual)
//
// 0 means empty seat, 1 means occupied seat.
//
// 1) Count how many seats are occupied.
// 2) Count how many seats are empty.
// 3) Print the coordinates (row, col) of every occupied seat.
//
// This is a very common "grid scanning" pattern.
int[][] seats =
{
{0, 0, 1, 0},
{1, 1, 1, 0},
{0, 0, 0, 0}
};
int occupied = 0;
int empty = 0;
for (int r = 0; r < seats.length; r++)
{
for (int c = 0; c < seats[r].length; c++)
{
if (seats[r][c] == 1)
{
occupied++;
System.out.println("Occupied at (" + r + ", " + c + ")");
}
else
{
empty++;
}
}
}
System.out.println("Occupied seats: " + occupied);
System.out.println("Empty seats: " + empty);
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Center (1,1): 4
Top-right (0,2): 7
Updated bottom-left (2,0): 99
3 5 7
1 4 9
8 6 2
Sum: 45
Max: 9
Even count: 4
Person 0 weekly total: 51600
Person 1 weekly total: 55900
Person 2 weekly total: 36000
Highest weekly total: Person 1
Total steps: 55900
Student 0 average: 90.0
Student 1 average: 81.5
Student 2 average: 92.0
Enter a student number (0-2): 1
Student 1 scores: 70 85 79 92
Occupied at (0, 2)
Occupied at (1, 0)
Occupied at (1, 1)
Occupied at (1, 2)
Occupied seats: 4
Empty seats: 8
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. In a 2D array, what do rows and columns represent?
  2. What is the difference between grid.length and grid[r].length?
  3. Why do we use nested loops to traverse a 2D array?
  4. In Task 4, why do we reset rowSum back to 0 for each new row?
  5. What is one real-world situation where a 2D array makes sense?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete