Using uninitialized array will contain a garbage value and using them will produce some unexpected results for you. To fix it, just simply initialize it:
// Initializing each element of array with 0.0 value
float yearsAvg[5] = {0.0};
printf("%f\n", yearsAvg[4]);
See it live on OnlineGDB.
Note: To initialize 1.0
or something else to all elements, {1.0}
will be no longer a valid syntax to achieve your desire. You have then two options here:
1. When different values are to be assigned in different array elements:
int my_array[3];
my_array[0] = 1;
my_array[1] = 5;
my_array[2] = 3;
2. Or, they are required to be initialized with a common value except zero:
int common_value = 50;
int my_array[5];
for (int i = 0; i < 5; i++)
my_array[i] = common_value;
Also, note that {3.5}
- such type of initialization is valid in C++, i.e. you can assign such values including zeroes in this manner.