# Re: "Variable Depth" Problem

none wrote:

<snip>

But how do you get a variable number of nested for-loops, or the logical equivalent of that?

"Programs and Data Structures in C", 2nd edition, Leendert Ammeraal, Wiley 1992, reprinted 1996, page 79, code cited "as is". There are a number of issues with the code that I am tempted to discuss, but I'll refrain, and simply quote what he wrote:

/* NESTED.C: A variable number of nested loops
*/
#include <stdio.h>
#define LEN 10
int n, r[LEN], lower[LEN], upper[LEN];

void print_r(void)
{ int i;
for (i=0; i<n; i++) printf("%6d", r[i]);
puts("");
}

void f(int k)
{ if (k == n) print_r(); else
for (r[k] = lower[k]; r[k] <= upper[k]; r[k]++)
f(k+1);
}

main()
{ int i;
printf("Enter n (not greater than %d): ", LEN);
scanf("%d", &n);
puts("Enter n pairs (lower, upper):");
for (i=0; i<n; i++)
scanf("%d %d", lower + i, upper + i);
puts("\nOutput:\n");
for (i=0; i<n; i++) printf(" r[%d]", i);
puts("");
f(0);
return 0;
}

He shows a demo run, but I'm not going to bother typing it. Instead, I'll compile the above and duplicate his results so that I can copy-paste them here. (In case you're wondering, that's a sort of self-check that I've copied his code correctly!)

Enter n (not greater than 10): 3
Enter n pairs (lower, upper):
5 7
2 2
8 9

Output:

r[0] r[1] r[2]
5 2 8
5 2 9
6 2 8
6 2 9
7 2 8
7 2 9

This doesn't /quite/ match Ammeraal's results - it looks like I missed a space somewhere, so my results don't line up quite as prettily as his - but the actual data are fine. As you can see, this is the equivalent of writing:

for(i = 5; i <= 7; i++)
for(j = 2; j <= 2; j++)
for(k = 8; k <= 9; k++)
printf("%6d %6d %6d\n", i, j, k);

Now WITHOUT changing a single line of code, let's go for the equivalent of:

for(i = 5; i <= 7; i++)
for(j = 2; j <= 2; j++)
for(k = 8; k <= 9; k++)
for(l = 3; l <= 5; l++)
printf("%6d %6d %6d %6d\n", i, j, k, l);

So we run the program again, without having to change it - all we do is specify different inputs:

Enter n (not greater than 10): 4
Enter n pairs (lower, upper):
5 7
2 2
8 9
3 5

Output:

r[0] r[1] r[2] r[3]
5 2 8 3
5 2 8 4
5 2 8 5
5 2 9 3
5 2 9 4
5 2 9 5
6 2 8 3
6 2 8 4
6 2 8 5
6 2 9 3
6 2 9 4
6 2 9 5
7 2 8 3
7 2 8 4
7 2 8 5
7 2 9 3
7 2 9 4
7 2 9 5

This may or may not be what you want, but I hope it's a step in the right direction.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
.