How to implement these loops ...

J. Horsmeier jos at and.nl
Fri Jun 21 18:50:02 AEST 1991


In article <12844 at skye.cs.ed.ac.uk> scm at lfcs.ed.ac.uk (Santa C Maria) writes:
>This is probably a rather silly question. I would be glad, if you
>can give me a hint. I want to implement a number of loops in this
>manner:
>   for ( i[0] = 0; i[0] < x[0]; ++i[0] ) {
>      for ( i[1] = 0; i[1] < x[1]; ++i[1] ) {
>	 ......
>	    for ( i[m-1] = 0; i[m-1] < x[m-1]; ++i[m-1] ) {
>	       do_something_here();
>	    }
[...]
>   }
>
>do_something_here() is thus executed x[0]*[x[1]* ... *x[m-1] times.
>The problem is that m, x[0], ... x[m-1] all depend upon run-time
>values. The question is how do I code this? 
>
>Thanks in advance for your help.


Hi there, try this one:


for (c= 0; c < m; i[c++]= 0);			/* All i[] to zero */

while (c != -1) {

	do_something_here();

	/* Next addition with carries */
	for (c= m-1; (c != -1)&&(i[c] >= x[c]-1); c--)
		i[c]= 0;

	/* Check on overflow */
	if (c != -1) 	
		i[c]++;

}

Hope this helps,


Jos


|O   J.A. Horsmeier AND Software B.V.        phone : +31 10 4367100   O|
|O                  Westersingel 106/108     fax   : +31 10 4367110   O|
|O                  3015 LD  Rotterdam NL    e-mail: jos at and.nl       O|



More information about the Comp.lang.c mailing list