I'm trying to initialize the last element in the array
int grades[10];
to grade 7 but it doesn't seem to work
I'm using C++ btw
I'm trying to initialize the last element in the array
int grades[10];
to grade 7 but it doesn't seem to work
I'm using C++ btw
The last element is grades[9]
, since arrays in C++ are zero-based (e.g. grades[0]
to grades[9]
are 10 elements). Is that what you're doing?
You might need to subtract one from the grade to use as your subscript value, or set the extent to one more.
Remember that an array with ten elements will have grades[0] through grades[9], and that grades[10] is an error.
If you want to initialize them all at definition:
int grades[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 };
If you want to initialize after:
int grades[10];
grades[9] = 7;
But, be aware that grades 0..8 will still be uninitialized, and will likely be junk values.
One more thing, if you initialize only the first element (if explicit array size is specified) or a shorter initiliazation list, the unspecified elements are fill with 0. E.g.
int grades[10] = {8}; //init with one element
is the same as:
int grades[10] = { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
or
int grades[10] = { 1, 9, 6, 16 }; //or init with a shorter than array size list with a minimum of 1 element
is the same as:
int grades[10] = { 1, 9, 6, 16, 0, 0, 0, 0, 0, 0 };
I find it handy for initializing an array with 0 values.
float coefficients[10] = {0.0f}; //everything here is full of 0.0f