Sunday, 18 August 2013

Assigning random values using ForEach to array doesnt work, but for statement works fine?

Assigning random values using ForEach to array doesnt work, but for
statement works fine?

If I use the foreach loop to assign values to an array randomly, it
assigns all 0's. But if change it to a normal for loop, it works fine.
Like below
Random random = new Random();
int[] a = new int[10];
for (int i = 0; i < 10; i++)
{
a[i] = random.Next(0, 10);
}
foreach (var item in a)
Console.WriteLine(item);
The output is fine, values are random
5
8
...
But, if I use a foreach loop to assign random values, the FIRST array item
has a random value and the rest are ALWAYS 0.... Why would that be?
foreach (var item in a)
{
a[item] = random.Next(0, 10);
}
foreach (var item in a)
Console.WriteLine(item);
this produces
8
0
0
0... all zeros follow
Why would a normal for loop work fine, but not a foreach loop? The same
foreach loops prints the values fine ?
Thank you

No comments:

Post a Comment