Loops
12 Mar 08, 7:50AM
Loops
There are several different approaches to creating a loop within C. The fastest is a do..while() loop, since it requires the least overhead if done correctly. However the most commonly used is a for() loop, which is where we'll start:
For Loops
The most usual form is:for(int i=1; i<=10; i++) { // ... do something ... }The part of particular interest is the first line, where the for(;;) loop is defined and the three arguments that are expect (always separated with a semi-colon):
- The first argument initialised (and perhaps declared) the counter variables. In this example we also declare the counter variable i here, which mean the variable i will be available only for this loop (as defined by the latest ANSI C standard). You don't have to declare or initialise anything here - just leave a space!
- The second parameter is a condition. Before running any commands (as signified by the '... do something...' block, this condition is checked. You can perform multiple checks or even none. The format is exactly the same as you would for any if() statement.
- The final parameter will be run at the end of each loop, so forms a natural place to incorporate an increment (or decrement) to your main counter variable.
for(int i=10; i>0; i--) { // ... do something ... }Compared to our previous example, this code requires one less instruction per loop, since the previous condition of 'i<10' is essentially turned into 'i-10<0', which clearly required two instructions to perform (one to subtract 10 from i; the second to see if this product less than zero).