C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

floating-point array. Because C is free-form, you can continue the initialization list over more than
one line, as is done for annualSal.


Click here to view code image


float money[10] = {6.23, 2.45, 8.01, 2.97, 6.41};
double annualSal[6] = {43565.78, 75674.23, 90001.34,
10923.45, 39845.82};

You also can define and initialize a character array with individual characters:


Click here to view code image


char grades[5] = {'A', 'B', 'C', 'D', 'F'};

Because a null zero is not in the last character element, grades consists of individual characters, but
not a string. If the last elements were initialized with '\0', which represents the null zero, you could
have treated grades as a string and printed it with puts(), or printf() and the %s conversion
code. The following name definition puts a string in name:


Click here to view code image


char italCity[7] = {'V', 'e', 'r', 'o', 'n', 'a', '\0'};

You have to admit that initializing such a character array with a string is easier to do like this:


Click here to view code image


char italCity[7] = "Verona"; /* Automatic null zero */

We should be getting back to numeric arrays, which are the primary focus of this chapter. Is there a
null zero at the end of the following array named nums?


int nums[4] = {5, 1, 3, 0};

There is not a null zero at the end of nums! Be careful—nums is not a character array, and a string
is not being stored there. The zero at the end of the array is a regular numeric zero. The bit pattern
(that’s fancy computer lingo for the internal representation of data) is exactly like that of a null zero.
But you would never treat nums as if there were a string in nums because nums is defined as an
integer numeric array.


Warning

Always specify the number of subscripts when you define an array. This rule has one
exception, however: If you assign an initial value or set of values to the array at the
time you define the array, you can leave the brackets empty:
Click here to view code image
int ages[5] = {5, 27, 65, 40, 92}; // Correct
int ages[]; // Incorrect
int ages[] = {5, 27, 65, 40, 92}; // Correct
Free download pdf