Open In App

How to Initialize a 2D Array in C?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C Program to initialize 2D array
#include <stdio.h>
  
// function to print the array
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()
{
  
    // directly initializing 2D array at the time of
    // declaration
    int arr1[3][4] = { { 1, 2, 3, 4 },
                       { 5, 6, 7, 8 },
                       { 9, 10, 11, 12 } };
  
    // printing array 1
    printf("printing arr 1 \n");
    print2DArray(3, 4, arr1);
  
    printf("\n");
    // runtime initialization
    int arr2[3][3];
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            arr2[i][j] = 0;
        }
    }
  
    /// printitng array 2
    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 




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads