C Initialize Array
To initialize an Array in C programming, assign the elements separated by comma and enclosed in flower braces, to the array variable. Initialization can be done during declaration itself or later in a separate statement.
In this tutorial, we will go through some examples of how to initialize arrays.
Array Initialization during Declaration
Method 1
We can assign the list of elements to the array variable during declaration. If we do not specify the size of array, the number of elements we are initializing the array with, becomes the size of array.
In the following example, we have not specified any size in the square brackets.
int arr[] = {2, 4, 6, 8, 10};
But, as we have assigned five elements to the array, the size of the array becomes 5
.
Method 2
We can also specify the size of array, and assign a list of elements to the array. The number of elements in the list could be less than the size specified. Then, the compiler creates array with specified size, and assigns the elements one by one from the starting of array.
int arr[10] = {2, 4, 6, 8, 10, 12, 14};
We have specified the array size to be 10
. But we have given only seven elements during initilaization. So, the first seven elements of the array get initialized with the given list of elements, and the rest of array elements are initialized to zero.
Method 3
We can also declare an array with a specific size and initialize later, one element at a time, using index.
int arr[10];
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;
arr[4] = 10;
Examples
In the following program, we initialize an array arr
with elements during declaration.
main.c
#include <stdio.h>
int main() {
int arr[] = {2, 4, 6, 8, 10};
for (int i = 0; i < 5; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
Output
2
4
6
8
10
Program ended with exit code: 0
In the following program, we declare an array of doubles of size 4, and initialize the elements later using index.
main.c
#include <stdio.h>
int main() {
double arr[4];
arr[0] = 0.54;
arr[1] = 2.31;
arr[2] = 2.14;
arr[3] = 8.67;
for (int i = 0; i < 4; i++) {
printf("%lf\n", arr[i]);
}
return 0;
}
Output
0.540000
2.310000
2.140000
8.670000
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to initialize an array in C programming with examples.