Sams Teach Yourself C in 21 Days

(singke) #1

Arrays: The Basics ..............................................................................................


Before we cover the forstatement, you should take a short detour to learn about the
basics of arrays. (See Day 8, “Using Numeric Arrays,” for a complete treatment of
arrays.) The forstatement and arrays are closely linked in C, so it’s difficult to define
one without explaining the other. To help you understand the arrays used in the forstate-
ment examples to come, a quick treatment of arrays follows.
Anarrayis an indexed group of data storage locations that have the same name
and are distinguished from each other by a subscript,orindex—a number follow-
ing the variable name, enclosed in brackets. (This will become clearer as you continue.)
Like other C variables, arrays must be declared. An array declaration includes both the
data type and the size of the array (the number of elements in the array). For example,
the following statement declares an array named datathat is type intand has 1,000 ele-
ments:
int data[1000];
The individual elements are referred to by subscript as data[0]throughdata[999]. The
first element is data[0], notdata[1]. In other languages, such as BASIC, the first ele-
ment of an array may be 1; this is not true in C. In C, the first element is indexed with
zero.

124 Day 6

NEWTERM

One way to look at the index number is as an offset. For the first item in the
array, you want to be offset by nothing (or zero). For the second item you
are offset by one item so the index is one.

Note


Each element of this array is equivalent to a normal integer variable and can be used the
same way. The subscript of an array can be another C variable, as in this example:
int data[1000];
int index;
index = 100;
data[index] = 12; /* The same as data[100] = 12 */
This has been a quick introduction to arrays. However, you should now be able to under-
stand how arrays are used in the program examples later in this chapter. If every detail of
arrays isn’t clear to you, don’t worry. You will learn more about arrays on Day 8.

10 448201x-CH06 8/13/02 11:20 AM Page 124

Free download pdf