Donate to Grow My Website (1 $ please)

  • You may choose specified posts to show it as featured posts with automatic sliding effects and keep visitors engaged for long time on your sites.
  • Dec 14, 2018

    2D Array Initialization in Data Structure - Learnengineeringforu

    2D Array Initialization in Data Structure - Learnengineeringforu

    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.

    No comments:
    Write Comments