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.
12. Breaking the Program
Answer:
-92
Breaking the Program
class MaxAlgorithm { public static void main ( String[] args ) { int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ; int max; // initialize the current maximum max = array[0]; // scan the array for ( int index=0; index < array.length; index++ ) { if ( array[ index ] > max ) // examine the current element max = array[ index ]; // if it is the largest so far, change max } System.out.println("The maximum of this array is: " + max ); } } |
Debugging a program is often difficult. Finding test cases that thoroughly test a program is an important part of this.
Of course, testing must be done with an actual running program and with actual data. Running a program once, with "toy" data, and saying that it works is not good enough for professional program development.
Compile and run the program. Once you have it running see if you can "break" it by initializing the array to different values, such as the following:
- Put the largest element at the beginning.
- Put the largest element at the end.
- Put in more than one copy of the largest element.
- Put in an extremely large element.
- Make all elements the same.
- Make all elements negative.
- Make all elements zero.
Is the correct maximum found in each case? Sometimes a program works for the data a programmer was thinking about when the program was written, but not for all the kinds of data the program is used with. This is why testing software often involves people other than those who wrote it.
Question 12:
Here is an interesting situation: change the test part of the
for
toindex < array.length-1
Now run the program again on the above test cases.
- Will the buggy program (with the changed loop) find the correct maximum of the data that is given in the original initializer list?
- When will the program not work correctly?
- Is it obvious that there is a bug?