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

Now, suppose score is declared in main as

int score[10];

and we make the call

sumList(score);

We can simply think that, in the function, score is known by the name num; any reference to

num is a reference to the original argument score.

The more precise explanation is this: since the name score denotes the address of score[0],

this address is passed to the function where it becomes the address of the first element of num,

num[0]. In fact, any address can be passed to the function where it will be taken to be the address

of num[0].

The function is free to assume any size it wishes for num. Obviously, this could land us in

trouble if we attempt to process array elements that do not exist. For this reason, it is good

programming practice to ‘tell’ the function how many elements to process. We do this using

another argument, as in:

int sumList(int num[], int n)

Now the calling function can tell sumList how many elements to process by supplying a value

for n. Using the declaration of score, above, the call

sumList(score, 10);

tells the function to process the first 10 elements of score (the whole array). But, and herein lies

the advantage of this approach: we could also make a call such as

sumList(score, 5);

to get the function to process the first 5 elements of score.

Using this function header, we write sumList as follows:

int sumList(int num[], int n) {

int sum = 0;

for (int h = 0; h < n; h++) sum += num[h];

return sum;

}

The function ‘steps through’ the array, from num[0] to num[n-1], using a for loop. Each time

through the loop, it adds one element to sum. On exit from the loop, the value of sum is returned as

the value of the function.

The construct

for (h = 0; h < n; h++)

is typical for processing the first n elements of an array.

212

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!