Skip to main content
ICT
Lesson A12 - Iterations
 
Main   Previous Next
 

B. Loop Boundaries page 4 of 18

  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 above is an example of a count type of boundary.

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

  1. 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 and then breaking out from the loop. You have already used the break statement for switch statements, and it has a similar use here. Once the loop encounters the break statement, all further checks of the boundary condition are ignored and code execution continues after the end of the while loop. For example, here is a loop that keeps a running total of non-zero integers, terminated by a value of zero.

    Scanner in = new Scanner(System.in);
    int total = 0;
    int number;

    while (true)
    {
      System.out.print ("Enter a number (0 to quit) --> ");
      number = in.nextInt();
      if(number == 0)
      {
        break;
      }
      else
      {
        total += number;
      }
    }
    System.out.println("Total = " + total);

    Notice that because we don’t know how many times we want the loop to run, we simply declare the boundary condition as always true. This means the loop will run until we tell it to stop with the break command.

  2. A similar construct to the break statement is the continue statement. When a loop encounters a continue statement, every statement left to execute in that specific iteration is ignored. The loop will then go back to check its boundary condition like normal. Continue statements can be useful for ignoring special cases (such as if you want to ignore an entry of zero in a loop that may use that number as a divisor).

     

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.