C Initializing 2D Array



We have already studied the multidimensional array in details. In this tutorial we will be studying different ways for Initializing 2D Array in C programming

Initializing 2D Array

We have divided the concept into three different types –
initializing 2D Array

Method 1 : Initializing all Elements rowwise

For initializing 2D Array we can need to assign values to each element of an array using the below syntax.

int a[3][2] = {
                 { 1 , 4 },   
                 { 5 , 2 },  
                 { 6 , 5 }   
              };

Consider the below program –

#include<stdio.h>

int main() {
   int i, j;
   int a[3][2] = { { 1, 4 },
                 { 5, 2 },
                 { 6, 5 }};

   for (i = 0; i < 3; i++) {
      for (j = 0; j < 2; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   return 0;
}

Output :

1 4 
5 2 
6 5 

We have declared an array of size 3 X 2, It contain overall 6 elements.

Row 1 :  { 1 , 4 },   
Row 2 :  { 5 , 2 },  
Row 3 :  { 6 , 5 }

We have initialized each row independently

a[0][0] = 1
a[0][1] = 4

Method 2 : Combine and Initializing 2D Array

Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially and row-wise

int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };

Consider the below example program –

#include <stdio.h>

int main() {
   int i, j;
   int a[3][2] = { 1, 4, 5, 2, 6, 5 };

   for (i = 0; i < 3; i++) {
      for (j = 0; j < 2; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   return 0;
}

Output will be same as that of above program #1

Method 3 : Some Elements could be initialized

int a[3][2] = {
                 { 1 },   
                 { 5 , 2 },   
                 { 6 }   
              };

Now we have again going with the way 1 but we are removing some of the elements from the array. In this case we have declared and initialized 2-D array like this

#include <stdio.h>

int main() {
   int i, j;
   int a[3][2] = { { 1 },
                 { 5, 2 },
                 { 6 }};

   for (i = 0; i < 3; i++) {
      for (j = 0; j < 2; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   return 0;
}

Output :

1 0 
5 2 
6 0

Uninitialized elements will get default 0 value.