This Java code example illustrates the use of a 2D array to perform basic operations. It initializes a grid, calculates the sum of each row, and finds the maximum element within the array. This example helps in understanding how to manipulate and traverse multidimensional arrays effectively.
public class MultiDimensionalArrayExample {
public static void main(String[] args) {
// Initializing a 2D array representing a grid
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Calculating the sum of each row
for (int i = 0; i < grid.length; i++) {
int rowSum = 0;
for (int j = 0; j < grid[i].length; j++) {
rowSum += grid[i][j];
}
System.out.println("Sum of row " + i + ": " + rowSum);
}
// Finding the maximum element in the 2D array
int max = grid[0][0];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
}
}
}
System.out.println("Maximum element in the grid: " + max);
}
}
This example highlights basic operations on a 2D array, including summing rows and identifying the maximum element.