Page 161 - DCAP507_SYSTEM_SOFTWARE
P. 161
Unit 10: Programming Languages Concept (I)
int i; Notes
for(i = 0; i < 10; i = i + 1)
a[i] = 0;
This loop sets all ten elements of the array a to 0.
Arrays are a real convenience for many problems, but there is not a lot that C will do with them
for you automatically. In particular, you can neither set all elements of an array at once nor
assign one array to another; both of the assignments
a = 0; /* WRONG */
and
int b[10];
b = a; /* WRONG */
are illegal.
To set all of the elements of an array to some value, you must do so one by one, as in the loop
example above. To copy the contents of one array to another, you must again do so one by one:
int b[10];
for(i = 0; i < 10; i = i + 1)
b[i] = a[i];
Remember that for an array declared
int a[10];
there is no element a[10]; the topmost element is a[9]. This is one reason that zero-based loops
are also common in C. Note that the for loop
for(i = 0; i < 10; i = i + 1)
...
does just what you want in this case: it starts at 0, the number 10 suggests (correctly) that it goes
through 10 iterations, but the less-than comparison means that the last trip through the loop has i set
to 9. (The comparison i <= 9 would also work, but it would be less clear and therefore poorer style.)
In the little examples so far, we've always looped over all 10 elements of the sample array a. It's
common, however, to use an array that's bigger than necessarily needed, and to use a second
variable to keep track of how many elements of the array are currently in use.
Example: we might have an integer variable
int na; /* number of elements of a[] in use */
Then, when we wanted to do something with a (such as print it out), the loop would run from 0
to na, not 10 (or whatever a's size was):
for(i = 0; i < na; i = i + 1)
printf("%d\n", a[i]);
Naturally, we would have to ensure that na's value was always less than or equal to the number
of elements actually declared in a.
Arrays are not limited to type int; you can have arrays of char or double or any other type.
LOVELY PROFESSIONAL UNIVERSITY 155