Arrays

I l @ ve RuBoard

Arrays

Arrays are important features in many programs. They enable you to store several items of related information in a convenient fashion. We will devote all of Chapter 10, "Arrays and Pointers," to arrays, but because arrays often are used with loops , we want to introduce them now.

An array is a series of values of the same type, such as 10 char s or 15 int s, stored sequentially. The whole array bears a single name , and the individual items, or elements, are accessed by using an integer index. For instance, the declaration

 float debts[20]; 

announces that debts is an array with 20 elements, each of which can hold a type float value. The first element of the array is called debts[0] , the second element is called debts[1] , and so on, up to debts[19] . Note that the numbering of array elements starts with 0, not 1. Each element can be assigned a float value. For example, you can have the following:

 debts[5] = 32.54; debts[6] = 1.2e+21; 

An array can be of any data type.

 int nannies[22];   /* an array to hold 22 integers        */ char actors[26];   /* an array to hold 26 characters      */ long big[500];     /* an array to hold 500 long integers  */ 

Earlier, for example, we talked about strings, which are a special case of char arrays. (A char array, in general, is one whose elements are assigned char values. A string is a char array in which the null character, \0 , is used to mark the end of the string. See Figure 6.6.)

Figure 6.6. Character arrays and strings.
graphics/06fig06.jpg

The numbers used to identify the array elements are called subscripts, indices, or offsets. The subscripts must be integers, and, as mentioned, the subscripting begins with 0. The array elements are stored next to each other in memory, as shown in Figure 6.7.

Figure 6.7. The char and int arrays in memory.
graphics/06fig07.jpg

Using a for Loop with an Array

There are many, many uses for arrays. Listing 6.17 is a relatively simple one. It's a program that reads in ten golf scores, which will be processed later on. By using an array, you avoid inventing ten different variable names , one for each score. Also, you can use a for loop to do the reading. The program goes on to report the sum of the scores and their average and a handicap, which is the difference between the average and a standard score, or par.

Listing 6.17 The scores_in.c program.
 /* scores_in.c -- uses loops for array processing */ #include <stdio.h> #define SIZE 10 #define PAR 72 int main(void) {   int index, score[SIZE];   int sum = 0;   float average;   printf("Enter %d golf scores:\n", SIZE);   for (index = 0; index < SIZE; index++)     scanf("%;d", &score[index]);  /* read in the ten scores */   printf("The scores read in are as follows:\n");   for (index = 0; index < SIZE; index++)     printf("%5d", score[index]); /* verify input           */   printf("\n");   for (index = 0; index < SIZE; index++)     sum += score[index];         /* add them up            */   average = (float) sum / SIZE;  /* time-honored method    */   printf("Sum of scores = %d, average = %;.2f\n", sum, average);   printf("That's a handicap of %.0f.\n", average - PAR);   return 0; } 

Let's see if Listing 6.17 works; then we can make a few comments. Here is the output:

 Enter 10 scores: Enter 10 golf scores:  102  98  112  108  105  103 99  101  96  102 100  The scores read in are as follows:   102   98  112  108  105  103   99  101   96  102 Sum of scores = 1026, average = 102.60 That's a handicap of 31. 

It works, so let's check out some of the details. First, note that although you typed 11 numbers, only 10 were read because the reading loop reads just 10 values. Because scanf() skips over whitespace, you can type all 10 numbers on one line or place each number on its own line, or, as in this case, use a mixture of newlines and spaces to separate the input. (Because input is buffered, the numbers are sent to the program only when you press the Enter key.)

Next, using arrays and loops is much more convenient than using 10 separate scanf() statements and 10 separate printf() statements to read in and verify the 10 scores. The for loop offers a simple and direct way to use the array subscripts. Notice that an element of a int array is handled like an int variable. To read the int variable fue , you would use scanf("%d", &fue) . Listing 6.17 is reading the int element score[index] , so it uses scanf("%d", &score[index]) .

This example illustrates several style points. First, it's a good idea to use a #define directive to create a manifest constant ( SIZE ) to specify the size of the array. You use this constant in defining the array and in setting the loop limits. If you later need to expand the program to handle 20 scores, simply redefine SIZE to be 20. You don't have to change every part of the program that uses the array size.

Second, the idiom

 for (index = 0; index < SIZE; index++) 

is a handy one for processing an array of size SIZE . It's important to get the right array limits. The first element has index , and the loop starts by setting index to . Because the numbering starts with , the element index for the last element is SIZE - 1 . That is, the tenth element is score[9] . Using the test condition index < SIZE accomplishes this, making the last value of index used in the loop SIZE - 1 .

Third, a good practice is to have a program repeat or "echo" the values it has just read in. This helps ensure that the program is processing the data you think it is.

Finally, note that Listing 6.17 uses three separate for loops. You might wonder if this is really necessary. Could you have combined some of the operations in one loop? The answer is yes, you could have done so. That would have made the program more compact. However, you should be swayed by the principle of modularity . The idea behind this term is that a program should be broken into separate units, with each unit having one task to perform. This makes a program easier to read. Perhaps even more important, modularity makes it much easier to update or modify a program if different parts of the program are not intermingled. When you know enough about functions, you could make each unit into a function, enhancing the modularity of the program.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net