Monday 28 March 2011

Nested Loops

Just a quick post today on nested loops.

The basic concept is that you will have one (or more) loop inside of another loop. Each internal loop will run and terminate, and then any external loops will then run. Here's an example:

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


The output would be:

i = 0
j = 0
j = 1
j = 2
j = 3
j = 4
i =1
j = 0
j = 1
j = 2
j = 3
j = 4
i =2
j = 0
j = 1
j = 2
j = 3
j = 4
i =3
j = 0
j = 1
j = 2
j = 3
j = 4
i =4
j = 0
j = 1
j = 2
j = 3
j = 4

So you see that it is really much like a normal loop. Each time a loop runs, it must execute all the code contained within its scope before looping again - even if it contains another loop.

This is just a quick basic concept that should be understood. This is very useful when dealing with multi-dimensional arrays (matrices), but I'll come to that in another lesson.

Sorry for the short post! I need to get back to studying for exams.

15 comments:

  1. reminds me of an old song called loop de loop.

    anyway this is very usefull for making array informtion as well as ordering stuff inside list and arrays.

    ReplyDelete
  2. C, good stuff. I always enjoyed dabbling in programming.

    ReplyDelete
  3. Nice post. Want more of these :)

    ReplyDelete
  4. Being a PHP programmer myself, I don't see how these could be useful, maybe I'm just inefficient? Mind shedding some light for me?

    ReplyDelete
  5. wish I could remember my programming

    ReplyDelete
  6. That's pretty interesting.

    ReplyDelete
  7. This format holds true for C++ as well?

    ReplyDelete
  8. It makes my brains go pfffffft.

    ReplyDelete
  9. Good walk through of how a nested loop works.

    ReplyDelete
  10. always wanted to learn this!

    ReplyDelete