nested loops

Started by
3 comments, last by return0 15 years, 8 months ago
Well I was reading a book on C++ and it slightly mentioned and explained nested loops, and I was wanting to fully understand them. Could any maybe tell me a good online tutorial for learning nested loops.
Advertisement
Its quite simple really, consider this example:
for(int i = 0; i < 10; ++i){    for(int j = 0; j < 10; ++j)    {            }}

The outer loop is set to execute 10 iterations. The inner loop is also set to execute 10 iterations.

Every time the outer loop "loops", the inner loop will loop 10 times. The total number of iterations is given by the number of times the outer loop "loops" multiplied by the number of times the inner loop "loops", giving us 100 iterations in total.

Loops can be nested to an arbitrary depth, though practically speaking there is surely a limit that is imposed by your compiler.
Just try writing a program to print out a 12x12 times table or something like that and you should get it.
Because I don't see how you could do it without using one?
Anyways, that's how I learned nested loops and what most books I've read use to demonstrate them.
[size="2"]Don't talk about writing games, don't write design docs, don't spend your time on web boards. Sit in your house write 20 games when you complete them you will either want to do it the rest of your life or not * Andre Lamothe
Let's say you have an array of employees, and for each employee you want to write "YOU'RE SO FIRED!" 3 times, you'll do this with nested loops:

const int employeeCount = 10;const int sayingCount = 3;for(int i = 0; i < employeeCount; ++i)  for(int j = 0; j < sayingCount; ++j)    puts("YOU'RE SO FIRED!");
I posted a practical example of where someone should be using nested loops in the last post of the thread linked to below; you should see why it makes things clearer.

Here.

This topic is closed to new replies.

Advertisement