Fence post problems:

Fence post problems arise when the endpoints are treated differently than the other values.

Example 14: A straightforward approach to outputting the integers between 1 and 10 separated by commas will have an extra comma on the end:

   int num = 1; 
   while ( num <= 10 ) { 
      System.out.print( num + ","); 
      num ++; 
} System.out.println();

The output for this code is: 1,2,3,4,5,6,7,8,9,10, note the trailing comma!

The problem here is that the number of numbers should be one more than the number of commas

   |~~~|~~~|~~~|~~~| 
|~~~|~~~|~~~|~~~|
There are three alternatives:

Alternative 1: Print the first fence post (number) before the loop:

   int num = 1;
   System.out.print(num);      
   num++;                       
   while ( num <= 10 ) {                           
      System.out.print("," + num); 
      num++;                      
   }
   System.out.println();

Alternative 2: Print the last post (number) after the loop:
   int num = 1;
   while ( num < 10 ) {
      System.out.print(num + ",");
      num ++;
   }  
   System.out.println(num);

Alternative 3: Guard the printing of the crosspiece inside the loop:
   int num = 1; 
   while( num <= 10) {
      System.out.print(num); 
      if ( num < 10 ) 
        System.out.print(","); 
      num++; 
   } 
   System.out.println();