Use Integers for Counting

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

double value ;
int tenths  = 0;
int inc     = 1;           // each "1" represents one tenth
 
while ( tenths  <= 100 )   // 100 tenths is 10.0
{
  value  = tenths/10.0 ;      // be sure to divide by a double 10.0
  System.out.println( "value:" + value );
  tenths =  tenths + inc ;
}
System.out.println( "done");

Use Integers for Counting

You might want a double or float for the loop control variable. You would add 0.1 to it each iteration. This would nearly work, but leads to errors. The value 0.1 cannot be accurately represented in binary. A loop that repeatedly adds 0.1 to a variable will accumulate errors.

Just for fun, here is a program fragment that does just that. Enter various limit amounts and see how much error there is:

// enter a value for limit
float inc   = 0.1 ;
float value = 0.0 ;

limit =  ;

while ( value < limit )  
{
  value = value + inc;
}
System.out.println( "Value was " + value + " when the loop ended");

Enter the limit value :    

QUESTION 13:

If you enter a limit of 10.0, what would be printed out if the arithmetic were perfectly accurate?