# compacting similar nested for loops

Discussion in 'C++' started by SplaTTer, Jul 2, 2003.

1. ### SplaTTerGuest

I have a piece of code consisting of k nested for loops, for example:

int k = 5;
int *p = new int[k];
double x,y; //x is read from file

for(p[0]=0;p[0]<=6;p[0]++)
for(p[1]=0;p[1]<=3;p[1]++)
for(p[2]=0;p[2]<=3;p[2]++)
for(p[3]=0;p[3]<=3;p[3]++)
for(p[4]=0;p[4]<=3;p[4]++)
y = assign(x, p);

This works, however, in a more general version k can be anywhere from
1 to 10. Therefore p will be of array size k and range from p[0] to
p[k-1], and I will only need k number of nested for loops. I could
write code for all the different possible conditions and use if
statements to select the proper one, but i would rather see if there
is a way to do it in a more compact manner (like with a recursive
function or even using the goto statement).

SplaTTer, Jul 2, 2003

2. ### Victor BazarovGuest

"SplaTTer" <> wrote...
> I have a piece of code consisting of k nested for loops, for example:
>
> int k = 5;
> int *p = new int[k];
> double x,y; //x is read from file
>
>
> for(p[0]=0;p[0]<=6;p[0]++)
> for(p[1]=0;p[1]<=3;p[1]++)
> for(p[2]=0;p[2]<=3;p[2]++)
> for(p[3]=0;p[3]<=3;p[3]++)
> for(p[4]=0;p[4]<=3;p[4]++)
> y = assign(x, p);
>
> This works, however, in a more general version k can be anywhere from
> 1 to 10. Therefore p will be of array size k and range from p[0] to
> p[k-1], and I will only need k number of nested for loops. I could
> write code for all the different possible conditions and use if
> statements to select the proper one, but i would rather see if there
> is a way to do it in a more compact manner (like with a recursive
> function or even using the goto statement).

Yes, recursion should work. And I've read it many times that any
recursion can be emulated with an array.

void nestedLoop(int p[], int upperlimit[],
unsigned level, unsigned maxlevel,
double& x, double &y)
{
if (level < maxlevel)
for (p[level] = 0; p[level] < upperlimit[level]; ++p[level])
nestedLoop(p, upperlimit, level+1, maxlevel, x, y);
else
y = assign(x, p);
}

....
int upperlimit[] = { 6,3,3,3,3 }; // not sure of the significance
// of the first one's being 6.
nestedLoop(p, upperlimit, 0, k, x, y);

(Is this right? I didn't test it)

Victor

Victor Bazarov, Jul 2, 2003

3. ### SplaTTerGuest

Thanks a bunch Victor. That worked great. There was only a small
problem with the for loops going to one less than each of the
upperlimits, but that was easily fixed.

the upperlimit array = {6,3,3,3,3}: the first loop is the most
important in my program, and 6 happens to be closer to +infinity than
3. So in other words it was just specific to what i'm using the
assign(x,p) function for.

Thanks,

-Kent

SplaTTer, Jul 2, 2003