Sign in to follow this  
mattnenterprise

nested loops

Recommended Posts

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this