C# – Creating Nested Loops with Loops

cloops

Is there a way to use a loop to create more nested loops? E.g. Doing this

for (int i = 0; i < iterations; i++)
            {
                //Do stuff
                for (int ii = 0; ii < iterations; ii++)
                {
                    // Do stuff
                    for (int iii = 0; iii < iterations; iii++)
                    {
                        //Do Stuff
                    }
                }
            }

but allowing the user to change how many nested loops you want during run-time.

This allows me to know the depth I am on, while also resetting the "i" counter back to 0, allowing me to do the exact same thing over again, but with a different depth value.

Best Answer

There is a way! You can solve such problems with recursion (https://en.wikipedia.org/wiki/Recursion_%28computer_science%29).

In your case it would look something like this (pseudocode):

function doStuff(int depth) {
    if(depth > USER_DEFINED_DEPTH)
        return;
    //Do stuff
    doStuff(depth + 1);
}

doStuff(0);
Related Topic