On Saturday 05 July 2003 23:21, Tristan wrote:
> I'm having some trouble figuring out how I can use the "for" function in
> my code, I've tried looking through the code and figuring out how past
> coders have done it but I've had no luck, can anybody please tell me how
> to use it? Thanks for your time.
Though I agree with the previous reply that yes, you probably should purchase
a book about C programming and read it, here is how you use the for loop:
The for loop has 3 parts: the initial state, the increment, and the condition
in this format:
for ( <initialization>; <condition>; <increment>)
{
//Your code goes here
}
The initilization should be something like
"i = 0"
or some pre-declared variable that you want to use in the loop.
The condition is checked before the loop starts, and should be something like:
"i < 5"
and the increment means what happens to a variable when one iteration of the
loop is over.
So, the order goes initlization - > condition - > loop body - > increment - >
condition - > loop body - > increment... so on.
Now that we know that, here is an example:
If you want to... say, add 1+2+3+4+5 using a for loop, do it like this:
int i;
int sum = 0;
for ( i = 1; i < 6 ; i++)
{
sum += i;
}
You can also make the loop decrement, increment, go in random order, have a
condition that has nothing to do with the initlization variable, etc. In
conclusion, the for loop is a flexable loop that can be used for many
purposes.