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

A. The while Loop page 3 of 18

  1. The general form of a while statement is:

    while (expression)
    {
      statement;
    }

    1. As in the if-else control structure, the boolean expression must be enclosed in parentheses ().

    2. The statement executed by the while loop can be a simple statement, or a compound statement blocked with braces {}.

  2. If the expression is true, the statement is executed. After execution of the statement, program control returns to the top of the while construct. The statement will continue to be executed until the expression evaluates to false.

  3. The following diagram illustrates the flow of control in a while loop:

  4. The following loop will print out the integers from 1-10.

    int number = 1;               // initialize

    while (number <= 10)          // loop boundary condition
    {
      System.out.println(number);
      number++;                   // increment/decrement
    }

  5. The above example has three key lines that need emphasis.

    1. You must initialize the loop control variable. If you do not initialize number, Java produces an error message warning you that the variable may not have been initialized.

    2. The loop boundary conditional test (number <= 10) is often a source of error. Make sure that you have the correct comparison (<, >, ==, <=, >=, !=) and that the boundary value is correct. Programmers have to ensure that the loop is executed exactly the correct number of times. Performing the loop one too many or one too few times is called an OBOB , Off By One Bug.

    3. There must be some type of increment/decrement or other statement so that execution of the loop eventually terminates, otherwise the program will get stuck in an infinite loop and never end!

  6. It is possible for the body of a while loop to execute zero times. The while loop is an entry check loop. If the condition is false due to some initial value, the statement inside of the while loop will never happen. This is appropriate in some cases.

 

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