Dynamic nested for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Dynamic nested for loop

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 loop levels, and max value void nestedLoop(int looplevel, int maxvalue) nestedLoop(1,2); // output 0 1 nestedLoop(2,2); // output 0,0 0,1 1,0 1,1 nestedLoop(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 there a way to write a function that can generate this "dynamic nested loops" behavior?

6th Nov 2018, 4:30 AM
<Mee_\t>
<Mee_\t> - avatar
4 Answers
+ 3
This is roughly what I had in mind: https://code.sololearn.com/cwAnlf77b9JE/#cpp
6th Nov 2018, 6:52 AM
Leif
Leif - avatar
+ 1
Recursion might do the trick. Base case would be looplevel 1. But you would have to write to memory first and pass it down the recursive calls.
6th Nov 2018, 5:43 AM
Leif
Leif - avatar
+ 1
Just rethinking, i think you can just pass the indexes down the calls in an array or vector. The base case would then have access to all indexes just like in a nested loop.
6th Nov 2018, 6:32 AM
Leif
Leif - avatar
+ 1
Great job dude Leif..
6th Nov 2018, 8:03 AM
<Mee_\t>
<Mee_\t> - avatar