To create a three-dimensional array in C, you need to specify the dimensions and initialize the array with the desired values. You can then use nested loops to iterate through each element of the 3D array.
In this example,
arr
with dimensions [2][2][2].#include <stdio.h>
int main() {
int arr[2][2][2] = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("arr[%d][%d][%d] = %d\n", i, j, k, arr[i][j][k]);
}
}
}
return 0;
}
arr[0][0][0] = 1 arr[0][0][1] = 2 arr[0][1][0] = 3 arr[0][1][1] = 4 arr[1][0][0] = 5 arr[1][0][1] = 6 arr[1][1][0] = 7 arr[1][1][1] = 8
In this example,
arr
with dimensions [2][3][4].#include <stdio.h>
int main() {
int arr[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
printf("arr[%d][%d][%d] = %d\n", i, j, k, arr[i][j][k]);
}
}
}
return 0;
}
arr[0][0][0] = 1 arr[0][0][1] = 2 arr[0][0][2] = 3 arr[0][0][3] = 4 arr[0][1][0] = 5 arr[0][1][1] = 6 arr[0][1][2] = 7 arr[0][1][3] = 8 arr[0][2][0] = 9 arr[0][2][1] = 10 arr[0][2][2] = 11 arr[0][2][3] = 12 arr[1][0][0] = 13 arr[1][0][1] = 14 arr[1][0][2] = 15 arr[1][0][3] = 16 arr[1][1][0] = 17 arr[1][1][1] = 18 arr[1][1][2] = 19 arr[1][1][3] = 20 arr[1][2][0] = 21 arr[1][2][1] = 22 arr[1][2][2] = 23 arr[1][2][3] = 24
In this tutorial, we learned How to create a Three Dimensional Array in C language with well detailed examples.