Different ways to Initialize all members of an array to the same value in C
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?
Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
Data_type array_name[size_of_array];
For example,
float num[10];
Below are some of the different ways in which all elements of an array can be initialized to the same value:
- 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] - 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} - Macros: For initializing a huge array with the same value we can use macros.
#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, x16intmain(void){// array declarationintnum[] = { x32, x8, x4, x1};intsize =sizeof(num)/sizeof(int);// 32+8+4+1= 45printf("The size of the array is %d\n", size);printf("The value of element in the array at index 5 is %d ",num[4]);return0;}Output:The size of the array is 45 The value of element in the array at index 5 is 1
- Using For Loop: We can also use for loop to initialize an array with the same value.
#include<stdio.h>intmain(void){intsize = 6;intval = 1;// array declarationintarr[size];inti;// initializing array elementsfor(i = 0; i < size ; i++){arr[i] = val;}// print arrayprintf("The array is:");for(i = 0; i < size ; i++){printf("%d ", arr[i]);}return0;}Output:The array is:1 1 1 1 1 1

