unit3 - Arrays Recall that an array is composed of a series of elements of one data type You use declarations to tell the compiler when you want an

unit3 - Arrays Recall that an array is composed of a series...

This preview shows page 1 - 4 out of 67 pages.

1 Arrays Recall that an array is composed of a series of elements of one data type. You use declarations to tell the compiler when you want an array. An array declaration tells the compiler how many elements the array contains and what the type is for these elements. Armed with this information, the compiler can set up the array properly. Array elements can have the same types as ordinary variables. Consider the following example of array declarations: /* some array declarations */ int main(void) { float candy[365]; /* array of 365 floats */ char code[12]; /* array of 12 chars */ int states[50]; /* array of 50 ints */ ... } The brackets ( [] ) identify candy and the rest as arrays, and the number enclosed in the brackets indicates the number of elements in the array. To access elements in an array, you identify an individual element by using its subscript number, also called its index. The numbering starts with 0. Hence, candy[0] is the first element of the candy array, and candy[364] is the 365th and last element. This is rather old hat; let's learn something new. Initialization Arrays are often used to store data needed for a program. For example, a 12-element array can store the number of days in each month. In cases such as these, it's convenient to initialize the array at the beginning of a program. Let's see how it is done. You know you can initialize single-valued variables (sometimes called scalar variables) in a declaration with expressions such as
Image of page 1