13,147,037 members (61,308 online)
Rate this:
See more:
Why is not The answer same following? Why is not The answer same following?

Normal coding :
```for (long i = 1; i <= 5; i++)
{
sum = sum * i;
}```

Parallel Coding :

`Parallel.For(1, 5, delegate(int i){ sum = sum * i; });`

result of parallel=24
result of Normal=120
why ?
Posted 3-Dec-11 10:08am
Updated 3-Dec-11 10:21am
v2
Monjurul Habib 3-Dec-11 16:22pm

Edited: Code block.

Rate this:

## Solution 1

In the parallel for loop the loop size is not inclusive to the loop where as in normal for loop the loop size included. Take look at for detail for Parallel Programming[^] MSDN article.
Rate this:

## Solution 2

Hi,

You have tried to parallize a calculation where the result of one iteration is dependent on the previous. If the sum was not used in the multiplication the value would not be transferred to the next iteration.
You can only parallize stuff where iterations have no relation to each other.

Your result may vary on the machine you run it on when you do it like this, the sum value needs closure th make sure it's not effected outside the loop.

Hope this helps.

Regards, AT
Rate this:

## Solution 3

The reason is,,,, the value of `sum` was changed from the 1st `for` loop and used again in the second block of codes. Try using 2 different variables like: `sum1` and `sum2`

Regards,
Eduard

Top Experts
Last 24hrsThis month
 OriginalGriff 315 CPallini 55 Graeme_Grant 50 RickZeeland 40 Jochen Arndt 30
 OriginalGriff 6,125 Graeme_Grant 5,101 ppolymorphe 1,984 Jochen Arndt 1,904 CPallini 1,855