int[][] matrixArr = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int
, float
, double
), not Strings, Objects, etc.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
new
keyword.
dataType[][] arrayName;
int[][] numbers;
arrayName = new dataType[rows][columns];
numbers = new int[2][3];
dataType[][] arrayName = new dataType[rows][columns];
int[][] numbers = new int[2][3];
0
for int
, 0.0
for float
etc).
arrayName[rowIndex][columnIndex] = value;
int[][] numbers = new int[2][3];
numbers[0][0] = 10;
numbers[0][1] = 20;
numbers[0][2] = 30;
numbers[1][0] = 40;
numbers[1][1] = 50;
numbers[1][2] = 60;
dataType[][] arrayName = {
{value1, value2, value3, ...},
{value4, value5, value6, ...},
...
};
int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
for(int i = 0; i < numbers.length; i++) {
for(int j = 0; j < numbers[i].length; j++) {
System.out.println(numbers[i][j]);
}
}
for(int[] row : numbers) {
for(int num : row) {
System.out.println(num);
}
}
numbers.length
β gives the number of rows.numbers[i].length
β gives the number of columns in the i-th row.public class MainApp1
{
public static void main(String[] args)
{
// 1. Declare, create, and initialize matrix array in a single line
int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
// 2. Access and print array elements using nested for-each loop
System.out.println("Numbers are:");
for (int[] row : numbers)
{
for (int num : row)
{
System.out.print(num + " ");
}
System.out.println(); // Move to next row
}
}
}
Numbers are: 10 20 30 40 50 60
public class MatrixAddition
{
public static void main(String[] args)
{
// 1. Declare and initialize two 2x3 matrices
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6}
};
int[][] matrix2 = {
{7, 8, 9},
{10, 11, 12}
};
// 2. Create a result matrix of the same size
int[][] sum = new int[2][3];
// 3. Perform matrix addition using nested for loop
for (int i = 0; i < matrix1.length; i++) // rows
{
for (int j = 0; j < matrix1[i].length; j++) // columns
{
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// 4. Print the result matrix
System.out.println("Result of Matrix Addition:");
for (int i = 0; i < sum.length; i++)
{
for (int j = 0; j < sum[i].length; j++)
{
System.out.print(sum[i][j] + " ");
}
System.out.println(); // Move to next row
}
}
}
Result of Matrix Addition: 8 10 12 14 16 18
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.