08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

Points to note about Program P8.1:

• Using #define, we set the symbolic constant MaxNum to 100; we use it to

declare the array and in the prompt for numbers. This makes the program

easy to modify if we change our mind and wish to cater for a different

amount of numbers.

• We enter the while loop when the number read is not 0. Inside the loop, we

add it to the sum, store it in the array, and count it. Each time we reach the

end of the loop, the value of n is the amount of numbers stored in the array

so far.

• On exit from the while loop, we test n. If it is still 0, then no numbers were

supplied and there’s nothing else to do. The program does not make the

mistake of trying to divide by n if it is 0. If n is positive, we confidently divide

the sum by it to find the average.

• The for loop ‘steps through’ the array, printing the numbers and their

differences from the average. Here, n is the number of elements of the array

that were actually used, not necessarily the entire array. The elements used

are num[0] to num[n-1].

• The program works out the sum of the numbers as they are read. If we need

to find the sum of the first n elements after they have been stored in the

array, we can do this with the following:

sum = 0;

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

Program P8.1 does the basics. But what if the user entered more than 100 numbers? Recall

that, as declared, the elements of num range from num[0] to num[99].

Now suppose that n is 100, meaning that 100 numbers have already been stored in the array.

If another one is entered, and it is not 0, the program will enter the while loop and attempt to

execute the statement

num[n++] = a;

Since n is 100, this is now the same as

num[100] = a;

But there is no element num[100] – you will get an “array subscript” error. When you start

working with arrays, you must be very careful that your program logic does not take you outside

the range of subscripts. If it does, your program will crash.

To cater for this possibility, we could write the while condition as

while (a != 0 && n < MaxNum) { ...

If n is equal to MaxNum (100), it means we have already stored 100 values in the array and

there is no room for any more. In this case, the loop condition will be false, the loop will not be

entered, and the program will not try to store another value in the array.

205

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!