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

  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 as 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
    }
  5. The above example has three key lines that need emphasis:

    1. You must initialize the loop control variable (lcv). If you do not initialize number to 1, Java produces an error message.
    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.
    3. There must be some type of increment or other statement that allows the loop boundary to eventually become false. Otherwise the program will get stuck in an endless loop.

  6. It is possible for the while loop to occur zero times. 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.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.