While Loop
Previous    Next    Home    Source    Package

Notes
  1. Syntax of a while expression:
    while ( <condition> ) { <body> }
    
  2. The while loop has no provision for initialization. Therefore, variables needing initialization, such as i in this case, must be declared and initialized outside the loop. Such variables will continue to be recognized after the loop terminates.
  3. The <condition> is an expression that evaluates to true or false as is the case in the for loop. The loop repeats as long as the condition is true. In this example, the loop repeats as long as the value of variable i is less than the value of another variable called iter.
  4. The while loop has no provision for post-processing. In this example, i is incremented in the expression
    text.append((i++)+" "); 
    
    where the extra parens around the i++ are not needed but are added to avoid confusion with the string concatentation operator + that follows it.
  5. The <body> is a sequence of expressions representing a program segment just as for the for loop. Expressions in the <body> are executed until the end is reached or a break statement is executed (in that case, the loop terminates no matter what). In this case the body prints to the output window the values of i while incrementing i by 1, then a newline, then the variable iter is incremented by 1.
  6. The for loop is usually used when the condition does not change from iteration to iteration. The while is usually used when the condition does change. A nice property of the for loop is that iterator variables are not known outside the loop.