How to Initialize a 2D Array in C?
Last Updated :
14 Feb, 2024
In C, a 2D Array is a type of multidimensional array in which data is stored in tabular form (rows and columns). It has two dimensions so it can store the data in two directions i.e. rows and columns. In this article, we will learn how to initialize a 2D array in C.
Initialize Two Dimensional Array in C
We can simply initialize a 2D array at the time of declaration by providing the values in curly braces {} using the below syntax:
Syntax to Initialize 2D Array in C
dataType arrayName[row size][column size]={
{row1col1, row1col2, ...},
{row2col1, row2col2, ...},
...
};
For runtime initialization, we need to use loops to assign values.
C Program to Initialize a 2D Array
The below program demonstrates the initialization of a 2D array in C.
C
#include <stdio.h>
void print2DArray( int rows, int cols, int arr[][cols])
{
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
printf ( "%d " , arr[i][j]);
}
printf ( "\n" );
}
}
int main()
{
int arr1[3][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
printf ( "printing arr 1 \n" );
print2DArray(3, 4, arr1);
printf ( "\n" );
int arr2[3][3];
for ( int i = 0; i < 3; i++) {
for ( int j = 0; j < 3; j++) {
arr2[i][j] = 0;
}
}
printf ( "printing arr 2 \n" );
print2DArray(3, 3, arr2);
return 0;
}
|
Output
printing arr 1
1 2 3 4
5 6 7 8
9 10 11 12
printing arr 2
0 0 0
0 0 0
0 0 0
Share your thoughts in the comments
Please Login to comment...