The for loop

4.4 The for loop

Java has a for statement which combines the three aspects of a loop (initialize, test and change) into one statement. It looks like this :
for (int count = 0; count <= 10; count++) 
{
    System.out.println(count);
} 
The following program prints a sequence of values in the left column and their logarithms in the right column.
import java.util.Scanner; //Needed for Scanner class

/**
 * This program demonstrates a
 * counter controlled for loop.
 */
public class LogTable
{
   public static void main(String[] args)
   {
      int maxValue;    // Maximum value to display

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      System.out.println("Table of sequence and their logarithms.");

      // Get the maximum value to display.
      System.out.print("Enter last number : ");
      maxValue = console.nextInt();

      for (int i = 1; i <= maxValue; i++)
      {
         System.out.println(i + "\t" + Math.log(i));
      }
   }
}
Output :
Enter last number : 6
1	0.0
2	0.6931471805599453
3	1.0986122886681098
4	1.3862943611198906
5	1.6094379124341003
6	1.791759469228055

No comments:

Post a Comment

Pages