08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

To use the function, consider the following code in main:

int sumList(int[], int), score[10];

for (int h = 0; h < 5; h++) scanf("%d", &score[h]);

printf("Sum of scores is %d\n", sumList(score, 5));

As usual, any function that wants to use sumList must declare it using a function prototype.

Note the use of int[] to indicate that the first argument is an integer array. If we wish, we could

use an identifier in declaring the prototype, as in:

int sumList(int list[], int);

The actual identifier used is not important. We could replace list by any valid identifier.

The for loop reads 5 values into the array. Note that since an array element is just like an

ordinary variable, we must write &score[h] in scanf to read a value into score[h].

Suppose the values read into score are as follows:

In printf, the call

sumList(score, 5)

will get the function to return the sum of the first 5 elements of score: that is, 24. You should

gather by now that, to find the sum of the first 3 elements, say, we can write

sumList(score, 3)

8.8 String – Array of Characters

In Section 2.7 we showed you how to store a string in a “character array.” Now that we know a bit

about arrays, we can explain how strings are actually stored.

In C, a string is stored in an array of characters. Each character in the string is stored in one

position in the array, starting at position 0. The null character,\ 0, is put after the last character. This

is done so that programs can tell when the end of a string has been reached. For example, the string

"Enter rate:"

is stored as follows (◊ denotes a space):

213

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!