Skip to main content
Lesson 9 - while Loops
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Loop Boundaries page 4 of 9

  1. The loop boundary is the Boolean expression that evaluates as true or false. We must consider two aspects as we devise the loop boundary:

    1. It must eventually become false, which allows the loop to exit.
    2. It must be related to the task of the loop. When the task is done, the loop boundary must become false.

  2. There are a variety of loop boundaries of which two will be discussed in this section.

  3. The first is the idea of attaining a certain count or limit. The code in section A.4 is an example of a count type of bounds.

  4. Sample problem: write a program fragment that prints the even numbers 2-20. Use a while loop.

  5. A second type of boundary construction involves the use of a sentinel value. In this category, the while loop continues until a specific value is entered as input. The loop watches out for this sentinel value, continuing to execute until this special value is input. For example, here is a loop that keeps a running total of positive integers, terminated by a negative value.

    int total = 0;
    int number = 1;      // set to an arbitrary value
                         //to get inside the loop
    while (number >= 0)
    {
      System.out.print ("Enter a number (-1 to quit) --> ");
      number = console.getInt();
      if (number >= 0)
        total += number;
    }
    System.out.println("Total = " + total);
    1. Initialize number to some positive value.
    2. The if (number >= 0) expression is used to avoid adding the sentinel value into the running total.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.