Goals

  • To understand loops
    • while loop
    • for loop
      • Nested loop
    • for-each loop
I do not like to repeat successes, I like to go on to other things. ~ Walt Disney

Loops

We use loops to repeatedly execute a block of code. There are two main types of loops:
counter controlled loops and sentinel controlled loops.

A counter controlled loop uses a counter to control the number of times it executes. We call each time a loop runs an iteration.

A sentinel-controlled loop uses a boolean expression or flag to indicate how many times to iterate. It will iterate until the boolean expression is false.

Note: You can use break; in any of these loops to exit out of a statement early.

Use loops to avoid copy and pasting code. Combine with a function for maximum impact.

while loop

The basic pattern:

Here is an example of a sentinel-controlled while loop.

Here is an example of a counter-controlled while loop.

Note: you can decided whether the counter should be updated before or after the code is executed. Beware of the difference.

Use while loops when you need to do something without counting.

for loop

A for loop is a counter-controlled loop. The counter declaration and increment are part of the loops syntax. The loop increments after each iteration.

You can do more than just increment the variable. You can decrement/ multiple/ divide, or whatever arithmetic your design requires.

for-each loop

There is a special type of for loop for working with collections. Collections are a generic way for referring to arrays, lists, and other data structures. They are handy because they require less typing.

The loop reads: for each item, with a given type, in the collection do what is included in the brackets. The type of the loop variable must match the type of the data stored in the collection.

The basic pattern:

A specific example:

The loop increments after each iteration.
You can use any math in the loop increment portion of the syntax

Nested loops

A nested loop is simply a loop inside of loop. We can add a loop anywhere where we can put "statements."

More on this later. . .