Unit 2b

There are three kinds of repetition statements:

  • while loop

  • for loop

  • for-each loop

Loop Control Structure Control Flow

  • The condition is checked

  • If the condition is true, the loop body is executed

  • This repeats as long as the condition is true

  • When the condition is false, the loop exits and proceeds to the next statement

The while Statement

while (condition)
    statement;
  • If the condition is true, the statement is executed. Then the condition is evaluated again.

How do we change the loop condition?

When using a loop, there is usually a variable associated witht the loop condition

    this is called the loop control variable

There are 3 steaps to creating a loop:

  1. Initialize the loop control variable

  2. Test the loop control variable

  3. Change the loop control variable within the loop body

Example:

A sentinel value indicates the end of the input.

The variable sum maintains a running sum