
Loop of loops. Any nice solution?
Hello, I have a problem which I'm not sure if there is a nice solution.
I need a sequence of loops imbedded one inside the other, with variable depth.
Well, here is an example. The following program will loop around all the
3-bit strings.
/****** loop3.c ********/
const int K=3;
main()
{
int m[K],n[K],i[K], j; for (j=0;j<K;j++) { m[j]=0; n[j]=2; }
for (i[0]=m[0]; i[0]<n[0]; i[0]++)
for (i[1]=m[1]; i[1]<n[1]; i[1]++)
for (i[2]=m[2]; i[2]<n[2]; i[2]++)
printf("Do something with %2i %2i %2i\n",i[0],i[1],i[2]);
Quote:
}
Now what if I want all the K-bit strings, where K is any integer?
Suppose I want to experiment with K=1...20. Do I have to supply 20
versions of source code with different numbers of 'for' statements?
Obviously, the following naive 'solution' does not work:
/****** looploop.c *******/
const int K=3;
main()
{
int m[K],n[K],i[K],j; for (j=0;j<K;j++) { m[j]=0; n[j]=2; }
for (j=0;j<K;j++)
for (i[j]=m[j]; i[j]<n[j]; i[j]++)
printf("Do something with %2i %2i %2i\n",i[0],i[1],i[2]);
Quote:
}
The reason this does not work can be seen easily from the following program
which is equivalent to loop3.c.
/******* goto3.c ********/
const int K=3;
main()
{
int m[K],n[K],i[K],j; for (j=0;j<K;j++) { m[j]=0; n[j]=2; }
i[0]=m[0]; l0:
i[1]=m[1]; l1:
i[2]=m[2]; l2:
printf("Do something with %2i %2i %2i\n",i[0],i[1],i[2]);
i[2]++;if(i[2]<n[2])goto l2;
i[1]++;if(i[1]<n[1])goto l1;
i[0]++;if(i[0]<n[0])goto l0;
Quote:
}
That is, the labels are not variable. However, I've found a solution
/****** gotoloop.c ******/
const int K=3;
main()
{
int m[K],n[K],i[K],j, l;
for (j=0;j<K;j++) { m[j]=0; n[j]=2; }
l=0;
start:
for (j=l+1;j<K;j++) i[j]=m[j];
{ for (j=0;j<K;j++) printf("%2i ",i[j]); printf("\n"); }
for (l=K-1;l>=0;l--)
{(i[l])++; if(i[l]<n[l]) goto start;}
Quote:
}
Apart from using 'goto', this program is not very illuminating, either.
(It helps the understanding a little bit by noting that l denote the current
layer of loop.) So is there a better solution?
---
Dept of Computer Sciences and Applied Mathematics
Aston University, Birmingham B4 7ET, UK