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:
- The initialization expression allows to assign some starting value to a variable that's going to change while the loop is running.
- In our real-life example, we could set a
stepsFromHome
variable to0
.
- In our real-life example, we could set a
- The controlling expression generally compares the variable's value to another value that will tell us when to stop. The loop will continue as long as it evaluates to
1
or true.- In our real-life example, we would continue as long as our
stepsFromHome
variable was less than3000
steps.
- In our real-life example, we would continue as long as our
- The update expression should change the value of the variable at some point during each iteration.
- In our real-life example, every iteration could be a "step" and we could increase the
stepsFromHome
variable by1
step each time.
- In our real-life example, every iteration could be a "step" and we could increase the
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: