2D Arrays in Java
Detailed Notes + Examples + Practice
Questions
What is a 2D Array?
• 2D array = Array of arrays
• Data is stored in rows & columns
• Syntax: int[][] arr = new int[rows][cols];
Why Use 2D Arrays?
• To store tabular data
• Example uses:
- Matrix operations
- Seating plans
- Game boards
- Tables
Declaration & Initialization
int[][] arr = new int[3][3];
int[][] arr2 = {
{1,2,3},
{4,5,6},
{7,8,9}
};
Accessing Elements
arr[row][col]
Example:
int x = arr[1][2]; // value = 6
Printing 2D Array
for(int i=0;i<[Link];i++){
for(int j=0;j<arr[i].length;j++){
[Link](arr[i][j] + " ");
}
[Link]();
}
Sum of All Elements
int sum=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
sum+=arr[i][j];
}
}
[Link](sum);
Diagonal Sum
int sum=0;
for(int i=0;i<3;i++){
sum+=arr[i][i];
}
[Link](sum);
Matrix Addition
int[][] c = new int[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j] = a[i][j] + b[i][j];
}
}
Transpose (Very Important)
int[][] t = new int[cols][rows];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
t[j][i] = a[i][j]; // swap indexes
}
}
Enhanced For Loop
for(int[] row : arr){
for(int col : row){
[Link](col+" ");
}
[Link]();
}
Practice Questions (1–5)
1. Print a 3x3 matrix
2. Find sum of all elements
3. Count even & odd numbers
4. Find largest element
5. Print diagonal elements
Practice Questions (6–10)
6. Print boundary elements
7. Row sum
8. Column sum
9. Transpose matrix
10. Add two matrices