Foreach loop behaviour and manipulation

Binarydepth binarydepth at gmail.com
Mon Dec 2 06:54:23 PST 2013


On Friday, 29 November 2013 at 09:15:28 UTC, Joseph Rushton 
Wakeling wrote:
> On 29/11/13 00:36, Binarydepth wrote:
>> I'm wondering in the case of manipulating the variable from 
>> the foreach loop, Do
>> I have to reset that variable so the loop can work as intended 
>> ?(chronologically).
>
> I think that you are approaching this problem in the wrong way.
>  Instead of using a temporary variable to preserve the loop 
> value, why not keep the loop value constant (immutable, in 
> fact) and use a temporary variable to calculate the values that 
> you wish to write to the array?
>
> Like so:
>
> ////////////////////////////////////////////////////////////////////////
> import std.stdio : write, readf;
> void main()
> {
>     int a, r, f;
>     int[102] arr;
>     write("Digite su año de nacimiento : ");
>     readf(" %d", &a);
>     write("\n");
>     foreach (immutable t; 1 .. 51)
>     {
>         int temp = (((t * 20) + 420) * 5) + 3;
>         arr[t - 1] = temp - a;
>         temp = (((t * 5) + 50) * 20) + 1013;
>         arr[t] = temp - a;
>     }
>     write("BD\tAnonimo\n");
>     foreach(count; 0..102)
>     {
>         write(arr[count]);
>         if(count%2==0)
>             write("\n");
>         else
>             write(" : ");
>     }
> }
> ////////////////////////////////////////////////////////////////////////
>
> This gives same results as your existing code but (to me at 
> least) is much simpler and easier to follow.
>
> 2nd thing -- do I assume right that you are getting incorrect 
> output and that the later output values shouldn't be all zero?  
> I think this is because you are incorrectly choosing array 
> indexes to write to, but we should perhaps talk about what your 
> program is _supposed_ to do before addressing that.
>
> Am I also right to assume that you're used to languages where 
> the array index starts from 1 rather than from 0?
>
> Best wishes,
>
>     -- Joe

Completely agree with you. That's actually what I ended up doing. 
:)


More information about the Digitalmars-d-learn mailing list