let's say there is a function

void cicl(){ for(...){ for(...){ ` for(...){ cout << "работает вложенных три цикла" << endl; } `} } } 

and if you need a function that creates 10,000 nested loops.

 void cicl(unsigned int num_cicle=10000){ // не будем же мы здесь писать 10000 вложенных циклов } 

How to implement this without resorting to recursion ?

  • even a hint of an example of use? what for? - spirit
  • 2
    Some terribly crazy task. Considering that only the inner loop is spinning. - alexlz 5:56 pm
  • 10,000 nested loops with n iterations is one loop with 10,000 ^ n iterations. and in the question the truth is one cycle - internal. - Yura Ivanov
  • I cited while an example, and for all the cycles I thought it was perfect - perfect
  • I will correct it so that it is clear - perfect

2 answers 2

If you need to organize nested loops, then you only need an array to store the indices.

Suppose you need n nested loops, but the maximum value is m.

 #include <iostream> #include <cmath> using namespace std; int main() { const int n = 3; const int m = 4; int ind[n] = {0}; int c = pow(m,n); // степень, может быть вычислена сразу. for (int i = 0; i < c; i++) { // это такое тело цикла - вывод индеков for (int j = 0; j < n; j++) { std::cout << ind[j] << " "; } std::cout << std::endl; // ключевая часть - обновим индексы for (int j = 0; j < n; j++) { ind[j]++; if (ind[j] < m) break; ind[j] = 0; } } return 0; } 

If the indices should be different, then another array of indices is needed and the checks should not be with m, but with the elements of this array.

This code has many flaws, for example, you can get rid of the cycle parameter i (with large nesting there can be overflow). But it is easy if you want to modify. Also, you may need to use a vector. But I will not do all the code for you :)

In fact, it is identical to the usual positional number system.

  • The idea is clear, it suits me - perfect
  • @perfect is an example of avoiding a heap of nested loops and recursion HC # 107519 . That is what the @KoVadim answer is about. - Yura Ivanov

Any recursion can be organized through a while using the stack.

not in C ++, but Explicit stack usage

  • need no recursion, the stack is very limited - perfect
  • using the stack you can do without recursion. What exactly is it limited to? for complete understanding it would be good to have an example or description. - spirit