• Advertisement
Sign in to follow this  

nested loops

This topic is 3495 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!");

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement