Types of array in c programming





Here we have two type of array :

  • One-dimensional array in c
  • Multi-dimensional array in c


  1. One-dimensional array

    In C, a one-dimensional array is a collection of elements of the same data type arranged in a contiguous block of memory. You can declare and initialize a one-dimensional array using the following syntax:

        dataType arrayName[arraySize];
        

    Here's a Explaination:

    • dataType: Specifies the type of elements that the array will hold (e.g., int, float, char, etc.).
    • arrayName: The name you give to the array.
    • arraySize: The number of elements the array can hold. This value must be known at compile time and can be a constant or a defined constant expression.


    For example, to declare an array of integers with 5 elements:

        int numbers[5];
        


    You can also initialize the array during declaration:

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


    You can access individual elements of the array using their index. In C, array indexing starts from 0. For example:

        int thirdElement = numbers[2]; // Accessing the third element (index 2) of the array
        


    Note : Keep in mind that C does not perform bounds checking, so accessing elements beyond the bounds of the array can lead to undefined behavior or segmentation faults.



  2. Multi-Dimensional Array

    In C, a multi-dimensional array is an array that has more than one dimension. The most common type of multi-dimensional array is a two-dimensional array, but C also supports arrays with three or more dimensions.



    Here's how you can declare and initialize multi-dimensional arrays in C:

        dataType arrayName[dimension1Size][dimension2Size]...[dimensionNSize];
        


    Each dimension can have its own size. For example, to declare a 2D array of integers with 3 rows and 4 columns:

        int matrix[3][4];
        


    You can initialize a multi-dimensional array during declaration using nested braces {}:

    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    


    You can access individual elements of the multi-dimensional array using multiple indices. For example, to access the element in the second row and third column:

    int element = matrix[1][2]; // Row 1, Column 2 (indices start from 0)
    


    For multi-dimensional arrays with more than two dimensions, you simply add more sets of square brackets. For example, a 3D array:

    int threeDArray[2][3][4];
    

    And so on for higher dimensions.