Open In App

Different ways to Initialize all members of an array to the same value in C

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it.

int num[100];

How to declare an array in C?

Data_type  array_name[size_of_array];

For example,

float num[10];

Initializing all members of an array to the same value can simplify code and improve efficiency.

Below are some of the different ways in which all elements of an array can be initialized to the same value:

  1. Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.
    int num[5] = {1, 1, 1, 1, 1};
    This will initialize the num array with value 1 at all index. We may also ignore the size of the array:
    int num[ ] = {1, 1, 1, 1, 1}
    The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.
    int num[5] =  { };                // num = [0, 0, 0, 0, 0]
    int num[5] = { 0 }; // num = [0, 0, 0, 0, 0]
  2. Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers. [ first . . . last ] = value;
    int num[5]={ [0 . . . 4 ] = 3 };               // num = { 3, 3, 3, 3, 3}
    We may also ignore the size of array:
    int num[  ]={ [0 . . . 4 ] = 3 };               // num = { 3, 3, 3, 3, 3}
  3. Macros: For initializing a huge array with the same value we can use macros. C
    #include<stdio.h>
    
    #define x1 1
    #define x2 x1, x1
    #define x4 x2, x2
    #define x8 x4, x4
    #define x16 x8, x8
    #define x32 x16, x16
    
    int main(void)
    {
    // array declaration
    int num[] = { x32, x8, x4, x1};
    int size = sizeof(num)/ sizeof(int);    // 32+8+4+1= 45
    
    printf("The size of the array is %d\n", size);
    printf("The value of element in the array at index 5 is %d ", 
                                        num[4]);
    
    return 0;
    
    }
    

    Output
    The size of the array is 45
    The value of element in the array at index 5 is 1
    
  4. Using For Loop: We can also use for loop to initialize an array with the same value. C
    #include<stdio.h>
    
    int main(void)
    {
        int size = 6;
        int val = 1;
    
        // array declaration
        int arr[size];
        int i;
    
        // initializing array elements
        for (i = 0; i < size ; i++){
            arr[i] = val;
        }
    
         // print array
         printf("The array is:");
         for (i = 0; i < size ; i++){
             printf("%d ", arr[i]);
        }
    
        return 0;
    }
    

    Output
    The array is:1 1 1 1 1 1
    


Next Article

Similar Reads