-
Notifications
You must be signed in to change notification settings - Fork 1
TwoDimensionalArrays
Zhamri Che Ani edited this page Dec 23, 2024
·
3 revisions
- Matrix Representation: Useful in representing grids, matrices, or tables.
- Game Boards: For board games like chess and tic-tac-toe.
- Image Processing: Represent pixel values of an image.
int[][] zhamriArray;
With size:
zhamriArray = new int[3][4]; // 3 rows and 4 columns
With values:
int[][] zhamriArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OR
int[][] zhamriArray = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int value = zhamriArray[1][2]; // Gets the element in 2nd row and 3rd column
zhamriArray[0][0] = 10; // Sets the element in the 1st row and 1st column to 10
-
zhamriArray.length
gives the number of rows. -
zhamriArray[rowIndex].length
gives the number of columns in a specific row.
for (int i = 0; i < zhamriArray.length; i++) { // Rows
for (int j = 0; j < zhamriArray[i].length; j++) { // Columns
System.out.print(zhamriArray[i][j] + " ");
}
System.out.println();
}
for (int[] row : zhamriArray) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] zhamriArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the 2D array
for (int i = 0; i < zhamriArray.length; i++) {
for (int j = 0; j < zhamriArray[i].length; j++) {
System.out.print(zhamriArray[i][j] + " ");
}
System.out.println();
}
}
}
Output
1 2 3
4 5 6
7 8 9
public class Test2D {
private static int[][] zhamriArray;
public static void main(String[] args) {
myInput();
zhamriArray[2][1] = arrayAddition(zhamriArray[1][2], zhamriArray[2][2]);
myOutput();
}
public static void myInput() {
zhamriArray = new int[][]{
{1, 2, 3, 100},
{4, 5, 6, 100},
{7, 8, 9, 100}
};
}
public static int arrayAddition(int a, int b) { // a = 6, b = 9
int result = a + b;
return result;
}
public static void myOutput() {
for (int i = 0; i < zhamriArray.length; i++) {
for (int j = 0; j < zhamriArray[i].length; j++) {
System.out.print(zhamriArray[i][j] + " ");
}
System.out.println();
}
}
}
Output
1 2 3 100
4 5 6 100
7 15 9 100
Java supports arrays with more than two dimensions, e.g., 3D arrays, but they are rarely used due to increased complexity.
Example
int[][][] zhamriArray;
YouTube Channel --> MyNotes
Topic 3: Numerical Computation & Expression
Topic 4: Selection Control Structures
Topic 7: Arrays
Case Study