Jeungwoo Park
Jeungwoo Park

Reputation: 117

How to design a variable number of nested for-loops?

How to keep adding for-loop n times?

For example, if n = 3 then for-looping 3 times like below:

for() 
 {
  for()
   {
    for()
     {
      //keep adding for-loops depending on n
     }
   }
 }

I speculate that recursion might work. Any ideas?

Upvotes: 2

Views: 106

Answers (1)

Xiobiq
Xiobiq

Reputation: 400

void recursiveForLoops(int n, int limit)
{
    int i;
    if(n == 0)
    {
        //do something
        return;
    }
    for(i = 0; i < limit; ++i)
    {
        recursiveForLoops(n - 1, limit);    
    }
}

This will generate n nested for loops, each one iterating limit times. You could accomplish the same output using a regular, single for loop with a for(i = 0; i < k; ++i) where k is limit^n (limit to the n'th power).

Upvotes: 3

Related Questions