I konw the three dimensional (3D) array can be thought of as an array of arrays of arrays. And i have int[3][4][2] 3Darray i can initialize using for loop
Example
public class JavaProgram
{
public static void main(String args[])
{
int arr[][][] = new int[3][4][2];
int i, j, k, num=1;
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<2; k++)
{
arr[i][j][k] = num;
num++;
}
}
}
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<2; k++)
{
System.out.print("arr[" +i+ "][" +j+ "][" +k+ "] = " +arr[i][j][k]+ "\t");
}
System.out.println();
}
System.out.println();
}
}
}
output look like
And i have 3d Array like
int[][][] matrix = {{{1, 2, 3},{4, 5, 6}}, {
{10, 20, 30},{40, 50, 60}}};
And i not able to find out position all elements like matrix[0][0][0]=1. What is index value of other elements. please any one help me to find
Just iterate over the array as you did in your example but use the length
-attribute:
int[][][] matrix = { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 10, 20, 30 }, { 40, 50, 60 } } };
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
for (int k = 0; k < matrix[i][j].length; k++)
{
System.out.print("matrix[" + i + "][" + j + "][" + k + "] = " + matrix[i][j][k] + "\t");
}
System.out.println();
}
System.out.println();
}
If you want to access a specific element, you can also use length
to find out which range is valid. You can find more information here .
This is your array:
int[][][] matrix = { //-------------------Start of your first array contains two elements as 2D array.
{ //----------First element of First array, which contains two 1D array.
{ 1, 2, 3 }, //First element of 2D array.
{ 4, 5, 6 } //Second element of 2D array.
}, //First element of 3D array ends here.
{ // Second element of 3D array contains 2 1D array.
{ 10, 20, 30 },
{ 40, 50, 60 }
}
};
Now if you want to get position of any number, Take example I want the position of 20:
Now if you want to go with the complete loop. use length to find out the array length which will act as your index.
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
for (int k = 0; k < matrix[i][j].length; k++)
{
System.out.print("[" + i + "][" + j + "][" + k + "] = " + matrix[i][j][k] + "\t");
}
System.out.println();
}
System.out.println();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.