- Forward


Testing and Debugging Loops


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • Desk Checking:
    • Verifying that a program satisfies specifications by carefully reading the code
  • Testing:
    • Verifying that a program satisfies specifications by executing the code
  • Debugging:
    • Locating and repairing logic errors
Desk Checking Loops
Back SMYC Forward

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; }
Desk Checking Loops (cont.)
Back SMYC Forward

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; }
Desk Checking Loops (cont.)
Back SMYC Forward

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) { // ... }
Desk Checking Loops (cont.)
Back SMYC Forward

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++; }
Desk Checking Loops (cont.)
Back SMYC Forward

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; }
Desk Checking Loops (cont.)
Back SMYC Forward

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++); { // ... }
Desk Checking Loops (cont.)
Back SMYC Forward

Ensure that loop counters are initialized and/or re-initialized properly

int i; i = 1; while (i < 10) { // ... } while (i < 10) { // ... }
Testing Loops
Back SMYC Forward
  • An Observation:
    • A loop that is supposed to iterate n times might actually iterate 0 times, 1 time, n-1 times, n+1 times, or "forever"
  • Good Test Cases:
    • Will allow you to conclude that none of these "errors" can arise
Testing Loops (cont.)
Back SMYC Forward
  • An Observation:
    • for and while loops might have 0 iterations
  • An Example:
    • while (i < n) { // ... i = i + 1; }
  • Test Cases:
    • i = 0; and n = 10; ensures that the body is entered
    • i = 20; and n = 10; ensures that the body is not entered
Instrumenting Loops During Debugging
Back SMYC Forward
  • The Basics:
    • Include print() calls before while loops to see if the code will/should enter the body
    • Include print() calls (that include the variables that change) in the body of all loops
  • An Example:
    • javaexamples/basics/DebuggingLoops.java (Fragment: 0)
       
There's Always More to Learn
Back -