About Lesson
Initializing a 2D Array and Printing its Elements:
public class TwoDArrayExample1 {
public static void main(String[] args) {
// Initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the elements of the 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Calculating the Sum of Elements in a 2D Array:
public class TwoDArrayExample2 {
public static void main(String[] args) {
// Initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Calculate the sum of elements in the 2D array
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
// Print the sum
System.out.println("Sum of elements: " + sum);
}
}
Finding the Maximum Element in a 2D Array:
public class TwoDArrayExample3 {
public static void main(String[] args) {
// Initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Find the maximum element in the 2D array
int max = matrix[0][0];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
// Print the maximum element
System.out.println("Maximum element: " + max);
}
}