22 lines
1.5 KiB
HTML
22 lines
1.5 KiB
HTML
|
<p>
|
||
|
Usually algorithms need a way to express iteration, doing somethings multiple times until a condition is met.
|
||
|
In C we have 3 basic types of loops to achieve that. The for-loop, the while loop and the do-while loop.
|
||
|
</p>
|
||
|
<p>
|
||
|
The for-loop consist of the keyword <b>for</b>, followed by 3 expressions and then the statement or block, which should be iterated over.
|
||
|
The first expression is for the initialization. It will only be executed in the beginning. The second one is for the conditional check.
|
||
|
Only if it is evaluated to true, the code will be iterated over. This statement will be checked each time at the beginning of the loop.
|
||
|
The last expression is for everything, which needs to be done after one iteration. Usually the for-loop is used for counted-looping
|
||
|
in combination with a loop counter. But you can use them differently. E.g to iterate over a linked list.
|
||
|
</p>
|
||
|
<p>
|
||
|
The while loop consist of the keyword <b>while</b> followed by an expression for the conditional check and then by the statement or a block.
|
||
|
The while loop will first check, if the expression will evaluate to true. If that is the case, it will execute the code and check again until the
|
||
|
expression is false.
|
||
|
</p>
|
||
|
<p>
|
||
|
The do-while-loop works just like the while-loop, except that it will check the expression at the end of every iteration.
|
||
|
That's why the do-while-loop consist of the <b>do</b> keyword, then the statement or block and then the <b>while</b> keyword
|
||
|
with the expression for the conditional check.
|
||
|
</p>
|