JMU
Testing and Debugging Loops


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Desk Checking Loops

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.)

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.)

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.)

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.)

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.)

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.)

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

  int   i;

  i = 1;
  while (i < 10)
  {
      // ...
  }

  while (i < 10)
  {
      // ...
  }
  
Testing Loops
Testing Loops (cont.)
Instrumenting Loops During Debugging