Week 2 Meeting 3

While loop

A loop is a new kind of statement like a single branch if in that it has a conditional part and a branch part.  Unlike an if, it has only one branch – you either enter the branch or you don’t -- and, the tricky part, if you enter the branch, when you get to the end, you go back and evaluate the conditional part again.

 

Here is a control flow diagram for the while loop:

 

week05Notes03

 

Counters and Accumulators

A counter is a variable that is incremented each time through a loop.

An accumulator is a variable that accumulates a quantity, e.g., a sum.

 

For both counters and accumulators, the variable name appears on the left side of an assignment statement, and also as part of the expression on the right side of the same assignment statement.

Example:

Get and print 3 numbers from the user.  Use a counter to count to 3.

Get the number of numbers the user specifies.  Use a counter to count to the number of times the user specifies.

 

Indefinite loops

A loop that repeats a number of times that is not known.  The number of repetitions depends on something that is out of the program’s control, e.g.,

 

Read and print values until the user enters a negative number.

 

We sometimes call a value used to stop a loop a sentinel value.

 

The example above that repeated the number of times the user specified was an indefinite loop.