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

(Romina) #1
Note

sizeof() returns the number of bytes you reserved for the array, not the number of
elements in which you have stored a value. For example, if floating-point values
consume 4 bytes on your computer, an 8-element floating-point array will take a total
of 32 bytes of memory, and 32 is the value returned if you apply sizeof() to the
array after you define the array.

If you want to zero out every element of an array, you can do so with a shortcut that C provides:


Click here to view code image


float amount[100] = {0.0}; /* Zeroes-out all of the array */

If you don’t initialize an array, C won’t either. Until you put values into an array, you have no idea
exactly what’s in the array. The only exception to this rule is that most C compilers zero out all
elements of an array if you initialize at least one of the array’s values when you define the array. The
previous clue works because one value was stored in amount’s first element’s position and C filled
in the rest with zeroes. (Even if the first elements were initialized with 123.45, C would have filled
the remaining elements with zeroes.)


Putting Values in Arrays


You don’t always know the contents of an array at the time you define it. Often array values come
from a disk file, calculations, or a user’s input. Character arrays are easy to fill with strings because
C supplies the strcpy() function. You can fill other types of arrays a single element at a time. No
shortcut function, such as strcpy(), exists to put a lot of integers or floating-point values in an
array.


The following code defines an array of integers and asks the user for values that are stored in that
array. Unlike regular variables that all have different names, array elements are easy to work with
because you can use a loop to count the subscripts, as done here:


Click here to view code image


int ages[3];
for (i = 0; i < 3; i++)
{
printf("What is the age of child #%d? ", i+1);
scanf(" %d", &ages[i]); // Gets next age from user
}

Now let’s use a simple program that combines both methods of entering data in an array. This
program keeps track of how many points a player scored in each of 10 basketball games. The first six
scores are entered when the array is initialized, and then the user is asked for the player’s scores for
games 7–10. After all the data is entered, the program loops through the 10 scores to compute average
points per game:


Click here to view code image

Free download pdf