Thursday, May 21, 2009

So on to loops

Now that we have established if and else,

We can concentrate on the while, for, and do.

All of them essentially makes the program go back the the starting step, and will continue to do so until the cycle is broken.  Be careful of infinity loops, that is loops that never breaks.
That means your program will never end, always a bad thing.

The simplest is the while loop.

here is an example code, include the usually int main and all that nice stuff.


{int i;                (interger i)

i = 0;                  (i equals 0)

while (i <3,
1++};                                                                    (increase i by 1)

printf ("finished.\n");                                (print finished when out of loop)

return 0;}                          (stop program)

So there you have it the most basic of loop programming.  The "for" function is about the same as the while function, and I do not know the real basic difference between them.  I do know that for some programs "for" is better than "while" though like I said, I'm not sure why.
The "do" is the same, but the does it's execution at the end of the function instead of the beginning.

Now our program is actually starting to look like a real computer program.  It is running and we can stop it when we want.  You can even play around with the "if" and "else" to control the flow while in the loop.

Next time, we'll try to make a more complicated program.

No comments:

Post a Comment