H.A.9.1 o PP9

PROGRAMMING POINTERS, LESSON 9

 

 

Syntax/correctness issues

 

9-1        Make sure you initialize counters and totals before entering a while loop.

 

9-2        With looping problems it is very easy to exceed the INT_MAX limit of 2-byte integers.  When totaling large amounts of integers use long int variables.

 

9-3        Be careful when testing floating point values for boundary conditions in a loop.  Because floating-point numbers are stored imprecisely, comparisons with double values do not always work as expected.  For example, here is a sample program that results in an endless loop.

 

#include <iostream.h>

#include <iomanip.h>

 

main ()

{

         double x = 0.0;

         int  loop = 0;

 

         cout << setprecision (2) << setiosflags(ios::showpoint);

         while (x != 10.0)

         {

                 x += 0.1;

                 cout << setw(7) << x;

                 loop++;

                 if (loop % 10 == 0) cout << endl;        // do an endl every 10 values

         }

         return 0;

}

 

The run output looks like this:

 

0.10   0.20   0.30   0.40   0.50   0.60   0.70   0.80   0.90   1.00

1.10   1.20   1.30   1.40   1.50   1.60   1.70   1.80   1.90   2.00

 

... gets stuck in endless loop ...

 

             Because doubles are stored imprecisely, when it came time to compare (x != 10.0) the equality comparison was missed.  The boolean condition should be (x < 10.0).

 

 

Formatting suggestions

 

9-4        Line up the braces of a while loop with the keyword while.  Indent the statements inside of the while loop 3 spaces.  See the above program as an example.  

 

 


Software engineering

 

9-5        When setting up a sentinel-controlled loop, consistently remind the user of what the sentinel value is.

 

9-6        If you follow the guidelines of structured programming, avoid using the break command in conditional loops.  However, use of the break command will result in fewer steps executed.