11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 7: Storing Sequences in Arrays 97If the input value is negative, control exits the loop by executing the break. Ifnot, integerValue is copied into the array. The int variable numberOfValuesis used as an index into the array. numberOfValues was initialized to 0 upat the beginning of the for loop. The index is incremented on each iterationof the loop. The test in the for loop keeps the program from storing morethan the 128 integers allocated by the program. (The program goes immediatelyto the output portion after 128 entries whether or not the user enters anegative number.)The array inputValues is declared as 128 integers long. If you’re thinkingthat this is enough, don’t count on it. Writing more data than an array causesyour program to perform erratically and often to crash. No matter how largeyou make the array, always put a check to make sure that you do not exceedthe limits of the array.The main function ends by calling displayArray() to print the contents ofthe array and the sum.The Dev-C++ environment can help keep you and your functions straight.Figure 7-1 shows the contents of the Classes tab. The name and prototypeof each function appear there. Double-clicking a function name takes youstraight to the function in the .CPP source file.Figure 7-1:The Classestab displaysinformationabout thefunctionsthat makeup theprogram.The displayArray() function contains the typical for loop used to traversean array. Each entry in the array is added to the variable accumulator. ThesizeOfArray passed to the function indicates the number of values containedin integerArray.Notice, yet again, that the index is initialized to 0 and not to 1. In addition,notice how the for loop terminates before i is equal to sizeOfArray. Noneof the elements after the sizeOfArray element contains valid data. The outputappears as follows:

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

Saved successfully!

Ooh no, something went wrong!