I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » Tutorials » C & C++ » Basic »


john\′s Photo
12 Mar 08, 2:50AM
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.

As such the example above, starts at 1, and counts up to and includes 10.

Conditions matched to zero

If at all possible, you should always have a condition that related to zero. For example 'i>0' or 'i>=0' or 'i<0' etc. These conditions can be checked with a single machine code instruction and thereby reduce the overheads associated with a loop. Therefore the above loop can be achieved using i.e.
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).

While Loops

(to do...)
Currently you need to be logged in to leave a message.