More about the For Statement

This chapter discusses the 'for' loop in greater detail, as well as the scope of variables in the 'for' loop.

7. A Loop with an Integer Variable


Answer:

Yes. 1 + 1 is always exactly 2, with integers. (But you do need to worry about overflow when the
operands get too big.)

A Loop with an Integer Variable

Often a program uses an integer loop control variable which is used to compute a floating point x for every iteration of the loop. If you do this, floating point errors will not accumulate as the loop continues. (However, the floating point division that is done each time has only 64-bit accuracy.)

public class LogTable
{
  public static void main ( String[] args )
  {
    System.out.println( "x" + "\t ln(x)" );

    for ( int j = 1; j <= 20; j++ )
    {
      double x = j/10.0 ;
      System.out.println( x + "\t" + Math.log( x ) );
    }
  } 
}           

Here is its output:

x        ln(x)
0.1     -2.3025850929940455
0.2     -1.6094379124341003
0.3     -1.2039728043259361
0.4     -0.916290731874155
0.5     -0.6931471805599453
0.6     -0.5108256237659907
0.7     -0.35667494393873245
0.8     -0.2231435513142097
0.9     -0.10536051565782628
1.0     0.0
1.1     0.09531017980432493
1.2     0.1823215567939546
1.3     0.26236426446749106
1.4     0.33647223662121284
1.5     0.4054651081081644
1.6     0.4700036292457356
1.7     0.5306282510621704
1.8     0.5877866649021191
1.9     0.6418538861723947
2.0     0.6931471805599453

The result of dividing  j by 10.0 is not completely accurate. However, dividing an integer by a power of two, is accurate (as long as the result is not too small).

Question 7:

Is 8 a power of two?