Creating N nested for-loops

Andrew picture Andrew · May 17, 2015 · Viewed 7.7k times · Source

Is there a way to create for-loops of a form

for(int i = 0; i < 9; ++i) {
    for(int j = 0; j < 9; ++i) {
    //...
        for(int k = 0; k < 9; ++k) { //N-th loop

without knowing N at the compile time. Ideally I'm trying to figure out a way to loop through separate elements of a vector of digits to create each possible number if a certain amount of digits is replaced with different digits.

Answer

Razib picture Razib · May 17, 2015

You may use recursion instead with a base condition -

void doRecursion(int baseCondition){

   if(baseCondition==0) return;

   //place your code here

   doRecursion(baseCondition-1);
}  

Now you don't need to provide the baseCondition value at compile time. You can provide it while calling the doRecursion() method.