Style is that which indicates how the writer takes himself and what he is saying. It is the mind skating circles around itself as it moves forward. [Robert Frost]
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.
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.
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 / multiply / divide, or use whatever arithmetic your design requires.
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. . .