Foreach loop behaviour and manipulation

Binarydepth binarydepth at gmail.com
Tue Jan 7 13:08:42 PST 2014


On Thursday, 28 November 2013 at 23:45:26 UTC, H. S. Teoh wrote:
> On Fri, Nov 29, 2013 at 12:36:18AM +0100, Binarydepth wrote:
>> Hi guys I'm having some problems. Calculations are not working 
>> as
>> expected and I get segmentation fault. I used the 2.059 
>> version and
>> it runs after compilation on compileonline.com
> [...]
>> foreach(t; 1..51)
>>     {
>> 	temp=t;
>> 	t*=20;
>
> Modifying the loop variable of a foreach is, in general, a 
> risky move.
> If you need to make loop indices jump around, you should use a 
> plain for
> loop instead:
>
> 	for (t=1; t < 51; t++)
> 	{
> 		// modify t at will, just make sure your loop
> 		// condition(s) / loop increments still work correctly.
> 	}
>
> or, if the loop indices are truly wildly jumping around, use a 
> while
> loop:
>
> 	t = 1;
> 	while (t < 51 /* or whatever condition you may have */)
> 	{
> 		... // Do stuff
> 		t = ... // compute next index to jump to
> 	}
>
>
> T

This excersice is an example :

"Escriba un programa que determine los números (de cantidad de 
cifras par) divisores de 11
aplicando el siguiente concepto: cuando la suma de los dígitos 
alternos del número son iguales,
ese número es exactamente divisible por once. Por ejemplo 5841: 5 
+ 4 = 8 + 1, por lo tanto
el número 5841 es divisible por once."

The important part is "los números (de cantidad de cifras par)" 
The number of pair digits 10 to 99,  1000 to 9999, 100000 to 
999999, etc...

I immediately thought of this thread. Surely you can use a series 
of if inside the loop that will make it jump the undesired 
numbers.

or ... for(count=1;count>0 && count<100 || count>999 && 
count<10000 || etc...; count++ )


More information about the Digitalmars-d-learn mailing list