Common Array Algorithms
This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.
13. Classic Bug (3): Overlooking Boundaries
Answer:
- Will the buggy program (with the changed loop) find the correct maximum of the data that is given in the original initializer list?
- Yes—for this particular set of data, the program will compute the correct maximum.
- When will the program not work correctly?
- When the maximum element of the array is in the very last cell (and only occurs once in the array.)
- Is it obvious that there is a bug?
- No—for most data the program works OK. If it were tested just a few times, it might pass every test.
Classic Bug (3): Overlooking Boundaries
The change to the program introduces an off-by-one error. The array index does not go far enough to test the last cell of the array.
With a ten-element initializer list, the above buggy program will fail about one time in ten (assuming random lists of data). Failure might not be obvious, because the answer it computes is close to the maximum. With a ten thousand element array, the program will fail about one time in ten thousand! Sloppy testing will never find this bug. Off-by-one errors can be very subtle.
Classic Bug (3): Not testing the "boundaries". Bugs are often found at the boundaries: at the beginning and ends of loops, at the beginning and ends of data, with large or small values (or zero), with a very large amount of data, or with no data at all (which should not break the program).
Question 13:
What happens when the following code is run?
int[] myWeeklyPay = {769, 588, 1245, 309, 388, 902}; int sum = 0; for ( int j=0; j<=6; j++ ) sum += myWeeklyPay[j];