whiteiden97 - 4 years ago 83

C++ Question

I'd like to know if it is actually possible to create / define an homemade

`for`

"How to create a for loop like command in C++? #user9282's answer"

What I ask for is if we can make a

`for`

`for`

As example, here is a basic for-loop statement :

`for (int i = 0; i < 10; i++) { ... }`

I'm wondering if the new for-loop could

`int x = 20; // individual loops`

int y = 3; // = amount of for-loops performed (in this case, 3)

// maybe some code generating for-loops here or something...

// result:

for (int i = 0; i < x; i++)

{

for (int j = 0; j < x; j++)

{

for (int k = 0; k < x; k++)

{

// if "y" was equal to 5, there would be 2 more for-loops here

instructions; // we can use "i", "j", "k", ... here

}

}

}

Do you think this could be possible in c++ ?

[

In one sentence: I want to

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If you have *n* nested `for`

loops with the same bound *x*, you are performing *x*^{n} iterations. In that case, you can just use a single index and convert it into multiple indices for convenience. For *n* = 2, for example:

```
for (int z = 0; z < x * x; ++z) {
const int i = z / x;
const int j = z % x;
// ...
}
```

For *n* = 3:

```
for (int z = 0; z < x * x * x; ++z) {
// The last "% x" in this line is for illustration only.
const int i = (z / x / x) % x;
const int j = (z / x) % x;
const int k = z % x;
// ...
}
```

`i`

, `j`

, `k`

, etc. are the digits of the current iteration number `z`

converted to base `x`

. You could generalise this into a recursive function, or one that unpacks the digits into a `vector`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**