| Arrays An array lets you declare and work with a collection of values of the same type. For example, you might want to create a collection of five integers. One way to do it would be to declare five integers directly: int a, b, c, d, e; This is okay, but what if you needed a thousand integers? For 1 thousand : int a,b,c,d,e…………. or int a[1000]; An easier way is to declare an array of five integers: int a[5]; The five separate integers inside this array are accessed by an index. All arrays start at index zero and go to n-1 in C. Thus, int a[5]; contains five elements. For example: int a[5]; a[0] = 12; a[1] = 9; a[2] = 14; a[3] = 5; a[4] = 1; One of the nice things about array indexing is that you can use a loop to manipulate the index. For example, the following code initializes all of the values in the array to 0: #include <stdio.h> int main() { int a[5]; int i; for (i=0; i<5; i++) {a[i] = 0; printf("a[%d] = %d\n", i, a[i]);} getchar(); } Next Page >> |