The While loop

4.2 The While loop

The while loop repeatedly executes the same set of instructions while its controlling expression is true. Here is an example :
/**
 * This program demonstrates the while loop.
 */
public class WhileDemo
{
   public static void main(String[] args)
   {
      int count = 1;    // count is initiliazed

      while (count <= 10)    // count is tested
      {
         System.out.print(count + " ");
         count++;            // count is changed
      }
   }
}
Output :
1 2 3 4 5 6 7 8 9 10
The first statement in the loop prints value of count. The second statement uses the increment operator to add one to number. After it executes, the loop starts over. It tests the boolean expression again. If it is true, the statements in the body of the loop are executed. This cycle repeats until the boolean expression number <= 10 is false.
Loop in above example is controlled by a counter, above example is counter controlled loop. Loop in next example is a sentinel controlled loop, a special value (the "sentinel") that is used to say when the loop is done.
import java.util.Scanner;    // needed for Scanner class

/**
 * This program demonstrate sentinel
 * controlled while loop.
 */
public class AddNumbers
{
   public static void main(String[] args)
   {
      int value;      // to hold number
      int sum = 0;    // initialize the sum

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

      // Get the first value.
      System.out.print("Enter first integer (enter 0 to quit): ");
      value = console.nextInt();

      while (value != 0)
      {
         // Add value to sum
         sum = sum + value;

         // Get the next value from the user
         System.out.print("Enter next integer (enter 0 to quit): ");
         value = console.nextInt();
      }

      // Display the total.
      System.out.println("Sum of the integers: " + sum);
   }
}
Output :
Enter first integer (enter 0 to quit): 12
Enter next integer (enter 0 to quit): 3
Enter next integer (enter 0 to quit): 5
Enter next integer (enter 0 to quit): 0
Sum of the integers: 20

No comments:

Post a Comment

Pages