I\'m trying to figure out how I can use recursion to do n-level nested for loops. For example, if n=3, there would be 3 \'levels\'
for(z=0;z<6;z++){
fo
I came across this earlier today and thought I might share the solution that I eventually came up with. I'm not sure what the policy is here regarding replying to old posts. I'm just going by the fact that I came across this question this morning, and this kind of thing would have been useful to me.
For efficiency, I've avoided recursion. Also, it doesn't use any specific c++ stuff - it will work fine on C as well.
We're trying to create N nested "for" loops. Instead of using
for(int i = 0; i
I'll be replacing i, j, ... with an array: i[0], i[1], ..., i[n-1].
Here's my solution:
const int n = /*Insert N here: how many loops do you need?*/;
int i[n+1]; // if "n" is not known before hand, then this array will need to be created dynamically.
//Note: there is an extra element at the end of the array, in order to keep track of whether to exit the array.
for (int a=0; a
There, that's all. Hopefully the comments make it clear what it's meant to be doing. I think it should be pretty efficient - almost as much as real nested for-loops. Most of the overhead is a one-off at the beginning, so this should be more efficient that using recursive functions etc (please correct me if I'm wrong on this point).
Hope it's useful to somebody one day.
Peace and love.