Dynamically adding nested for loops

jrvbdeveloper

Member
Joined
Jul 15, 2007
Messages
17
Programming Experience
Beginner
Lets say I have a variable numLoops = 3. Now, I need 3 nested For loops. How would I go about doing this? Based on the value of numLoops, I need to have that many nested loops.

Thanks in advnace.
 
This is done using recursion... Here is a simple example :

VB.NET:
private function CallLoop(nTimesLeft as integer) as integer
    dim total as integer = 1

    if nTimesLeft > 0 then
        for i as integer = 0 to 1
            total += CallLoop(nTimesLeft - 1)
        next
    end if

    return total
end function

Now, suppose you call CallLoop(2), it will return 7 because it creates a tree with 1 root on level two, 2 branches on level one and 4 branches on level zero.

PS : If you encounter some StackException, it's because you forgot to put a condition that says to stop the loop and it went on calling methods one inside the other until the call stack collapsed.
 
Back
Top