Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic nested loops level

Tags:

c

algorithm

I'm trying to figure out a simple way to handle dynamic nested loops level. Consider the following function that takes in 2 parameters: #num of loops, and max value.

void PrintLoop(int maxloop, int maxvalue)

PrintLoop(1,2); 
// output
0
1

PrintLoop(2,2);
// output
0, 0
0, 1
1, 0
1, 1

PrintLoop(3,2);
// output
0, 0, 0
0, 0, 1
0, 1, 0
0, 1, 1
1, 0, 0
1, 0, 1
1, 1, 0
1, 1, 1

Etc...

Is there a way to write a function that can generate this "dynamic nested loops" behavior?

Thanks for any help

like image 967
Vu Duy Avatar asked Nov 15 '09 11:11

Vu Duy


People also ask

What is the maximum level of a nested for loop?

Save this answer. Show activity on this post. For CPython 3.7 (and previous CPython versions), the limit is 20.

How do I create a dynamic nested loop?

To implement a dynamic nested loop we need to increment the inner most loop variable until we run out values. Only then do we need to look at changing the upper level loop variables.

How many levels of nesting are allowed in Python?

Python imposes a limit of 20 nested blocks (not just loops, but this could be loops, or any other static block - including with, try/except and others ).

How many levels of nesting does C++ allow in looping statements?

A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.


1 Answers

Yes, it is possible, and to implement this a concept of "recursion" is often used:

void PrintLoop(int maxloop, int maxvalue)
{
   if (maxloop<=0) return ;
   // print something here...
   for (int i=0;i<maxvalue;i++){
      PrintLoop(maxloop-1, maxvalue);
      // After Recursion do something here...
   }
}
like image 132
P Shved Avatar answered Sep 26 '22 17:09

P Shved