Friday, 25 March 2011

Loops

Loops are useful for running one or more lines of code repeatedly. The basis of how a loop works is similar to an if statement: There is a condition, and if the condition fails, the loop stops. The first loop I'll show you is a called a while loop, here's its syntax:

while(condition)
{
    //code
}

Pretty simple. Let's see this in an example

int i=0;
while(i<10)
{
    printf("%d\n",i);
    i++;
}

(For those who don't know, i++ is the same as saying i=i+1 or i+=1. It means "increment i")
This will print out the numbers 0 to 9.
Basically we start by initializing an integer to 0. We tell our while loop "Loop the code while the value of i is less than 10". In the first pass, the condition passes the test because 0<10. Good! So we go ahead and call our printf function. Here's the important part: we increment i by 1. So now the value of i is equal to 1 and we return to the beginning of the while loop and run the condition again. Now we're asking "Is 1 less than 10?" Yes it is. We run the loop again. printf, increment, loop again: "Is 2 less than 10" Yes....you get the idea.
Let's look at the last pass through the loop, when i is equal to 9. "Is 9 less than 10?" Yes, so go into the loop, call printf and increment i. Now we go back to the top yet again, but this time we ask "Is 10 less than 10?"
The answer of course is NO, so we skip the loop entirely, just as we would if a condition in an if statement failed.

This is a simple use for a while loop, and in fact, while loops using a simple incrementing variable can be rewritten as another type of loop: a for loop. The syntax is a little more complicated, but in the end, for loops generally end up being easier to manage.

for(initial state;terminating condition;increment)
{
    //code goes here
}

Let's look back at our while loop example for a sec. See how we declared an integer i before the loop? That's our initial state. We then had a condition in the while loop. That of course is the terminating condition. At the end of the while loop, we increased the value of i. That's our increment.

Here's the same loop above rewritten as a for loop:

for(int i=0;i<10;i++)
{
    printf("%d\n",i);
}

Both loops essentially do the exact same thing. The real difference for you is that in a for loop, all the useful loop information is stored in the parentheses after the word "for".
Note that in the for loop, I declared my incrementing variable inside the parentheses. This is a matter of preference, but I do it whenever possible. Basically, I'm saying that the following is still correct:


int i;
for(i=0;i<10;i++)
{
    printf("%d\n",i);
}


While this is still correct, I find it very beneficial to declare your incrementing variable inside your loop. This way, the variable "dies" after the loop ends. This means that you can reuse that variable name for other loops and you don't have to worry about this loose variable floating around your program. This means that I could do this:


for(int i=0;i<200;i++)
{
    //run some code
}

for(int i=0;i<42;i++)
{
    //run some different code
}

And I won't have to worry about which variable I used before. Again, it really is a matter of preference. I showed you mine.

When writing loops, you'll likely accidentally code an infinite loop at some point. For example, take a look at this:

int x=5;
int y=2;
while(x==5)
{
    printf("...");
    y++;
}

With a quick look at the code, you'll see that our condition is always true! This means that the loop will never end. Likewise, the following will be an infinite loop.

while(1)
{
    //code
}

Thinking back to our logical operators, a logical statement return a value of 1 if true or 0 if false. Thus, our condition is interpreted as "While 'a true statement', run this code." No wonder it will loop forever!

It is also important to check your for loops for infinite loops, since for loops especially are usually not meant to be infinite.

for(int i=0;i>-1;i++)
{
}

will be an infinite loop since we are looping as long as i is greater than -1 and each time the loop runs, i is incremented. An infinite for loop can also be forced by writing:

for( ; ; )
{
}

No initial state, no terminating condition, no increment. The loop has noting to worry about and will go on forever.

Next time, I'll talk about nested loops

12 comments:

  1. :gototag

    echo infinite loops are kool

    goto gototag

    ReplyDelete
  2. Nice post, i'll follow for more. Been looking for good C tutorials.

    ReplyDelete
  3. Where were you when I needed you a couple years ago?

    ReplyDelete
  4. I always find it really interesting to compare the differences between Python and C. I literally had no knowledge of C til I started reading your blog. Thanks for everything!

    ReplyDelete
  5. Loops are something I've always hated. Don't know why, just always fu*k something up.

    ReplyDelete
  6. I might just check this out. Thanks for the info.

    ReplyDelete
  7. Thanks for the tips. I really need to get back into coding.

    ReplyDelete
  8. looks so much like java! so glad you're showing me this stuff.

    ReplyDelete
  9. infinite recursive loops are great for small programs to annoy other people.

    everytime someone says mac have no viruses i just program a quick script that keeps looping in an endless pop up madness.

    ReplyDelete
  10. Like these guys, I'm finding it really interesting to see the difference between the language I'm familiar with, Java, and yours, C. Thanks for the info man!

    ReplyDelete
  11. great guide sir! helped me out a bunch

    ReplyDelete
  12. greatest post known to blogdom.

    ReplyDelete