The structure of a while loop

 

A while loop allows us to define a code block that will execute repeatedly as long as some logical condition holds true.  The form that a while loop takes on is:

 

      while (logical condition)

      {

            // code block – the body of the loop

            // contains 0 or more statements

            statement 1

            statement 2

           

            statement n

      }

 

The way the loop works can be best understood by the figure below that shows the flow in the statement execution. 

As you can see, the conditional statement is evaluated first.  If it’s true, the statements in the code block defined by the loop (it’s called the body of the loop) are executed in sequence, before the condition is evaluated again.  If the condition is false, the statements in the body of the loop are skipped over, and execution proceeds with the next statement following the end of the block (indicated by the closing curly brace).  Terminology wise, each execution of the statements in the body of the loop is referred to as a loop iteration.