Testing and Debugging Loops
|
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
Ensure that you don't compare floating point numbers with the ==
operator
double total; total = 50.0; while (total != 0.0) { // ... total = total - 0.01; }
Ensure that you don't change the variable(s) used in the boolean
expression within the body of for
loops
int i; for (i=0; i<10; i++) { // ... i = i + 1; }
Ensure that you do change the variable(s) used in the boolean
expression within the body of while
and
do-while
loops
int i; i = 1; while (i < 10) { // ... }
Ensure that the correct variable is updated by the correct amount within the body of the loop
int i, j; i = 1; while (i < 10) { // ... j++; }
Ensure that the loop doesn't terminate early/late (especially "off by one")
int i; i = 1; // Loop ten times while (i < 10) { // ... i = i + 1; }
Ensure that you don't have a semicolon at the end of for
and/or while
loops
int i; for (i=0; i<10; i++); { // ... }
Ensure that loop counters are initialized and/or re-initialized properly
int i; i = 1; while (i < 10) { // ... } while (i < 10) { // ... }
for
and while
loops might
have 0 iterationswhile (i < n) { // ... i = i + 1; }
i = 0;
and n = 10;
ensures that the
body is enteredi = 20;
and n = 10;
ensures that the
body is not enteredprint()
calls
before while
loops to
see if the code will/should enter the bodyprint()
calls
(that include the variables that change) in the body
of all loops// Prompt for 10 numbers and find the total i = 1; n = 10; // For debugging: JMUConsole.printf("i: %d n: %d", i, n); while (i < n) { // For debugging: JMUConsole.printf("Iteration: %d", i); JMUConsole.printf("Enter a number: "); number = JMUConsole.readInt(); // For debugging: JMUConsole.printf(" BEFORE total:%d number:%d", total, number); total = total + number; // For debugging: JMUConsole.printf(" AFTER total:%d number:%d", total, number); ++i; }