How to Initialize a 3D Array in C?
Last Updated :
11 Mar, 2024
In C, a 3D array is a type of multidimensional array that stores data in a three-dimensional grid. It has three dimensions, allowing it to store data in three directions: rows, columns, and depth. In this article, we will learn how to initialize a 3D array in C.
Initializing Three Dimensional Array in C
We can initialize a 3D array at the time of declaration by providing the values in curly braces {}
using the following syntax:
Syntax to Initialize 3D Array in C
dataType arrayName[depth][row size][column size] = {
{
{depth0row0col0, depth0row0col1, ...},
{depth0row1col0, depth0row1col1, ...},
...
};
For runtime initialization, we need to use nested loops to assign values.
C Program to Initialize a 3D Array
The below program demonstrates the initialization of a 3D array in C.
C
#include <stdio.h>
void print3DArray( int depth, int rows, int cols,
int arr[][3][4])
{
for ( int i = 0; i < depth; i++) {
printf ( "Depth %d:\n" , i + 1);
for ( int j = 0; j < rows; j++) {
for ( int k = 0; k < cols; k++) {
printf ( "%d " , arr[i][j][k]);
}
printf ( "\n" );
}
printf ( "\n" );
}
}
int main()
{
int arr1[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 } } };
printf ( "Printing arr1 \n" );
print3DArray(2, 3, 4, arr1);
printf ( "\n" );
int arr2[2][3][4];
for ( int i = 0; i < 2; i++) {
for ( int j = 0; j < 2; j++) {
for ( int k = 0; k < 2; k++) {
arr2[i][j][k] = 0;
}
}
}
printf ( "Printing arr2 \n" );
print3DArray(2, 3, 4, arr2);
return 0;
}
|
Output
Printing arr1
Depth 1:
1 2 3 4
5 6 7 8
9 10 11 12
Depth 2:
13 14 15 16
17 18 19 20
21 22 23 24
Printing arr2
Depth 1:
0 0 0 0
0 0 0 0
0 0 0 0
Depth 2:
0 0 0 0
0 0 0 0
0 0 0 0
Time Complexity: O(N), where N is the total number of elements.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...