Erin's CS stuff

CS stuff!

Iteration

Iteration allows us to repeat blocks of code a bunch of times in a row.

Loops are used to implement iteration. To craft a loop, we must know what behavior or action(s) we're repeating and what state or value(s) is changing over time.

A real-life example is going for a run. The process we're repeating is moving one leg in front of the other more quickly than a walk. The "state" (or value) that changes over time is distance. This is important because before going for a run, we need to decide where our run starts and ends. Then, as long as we haven't reached our destination (and can still breath) we keep running! If we don't figure these things out, we either can't start running or will never stop (my personal nightmare)!

Syntax

In addition to the loop body, there are 3 components that should be included in each loop:

There are 3 types of loops in C, which rearrange these parts to make them more ideal for certain circumstances.

for

The for loop conveniently combines the required expressions in between the parenthesis. The general format is

for(expression1; expression2; expression3){
  //loop body
}
where expression1 is the initialization expression, expression2 is the controlling expression, and expression3 is the update expression.

Our real-life example would look like this:

while

The while loop includes the controlling expression between the parenthesis. The general format is

while(control expression){
  //loop body, which should include the update expression
}
and the initialization expression is assumed to be included before the loop.

Our real-life example would look like this:

do while

The do while loop moves the controlling expression to after the loop body. The general format is

do{
  //loop body, which should include the update expression
}while(control expression);
and again, the initialization expression is assumed to be included before the loop. DON'T FORGET THE SEMICOLON!

Our real-life example would look like this: