12,068,520 members (65,028 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 11:08am
Edited 3-Dec-11 11: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
 Dave Kreskowiak 290 CHill60 239 OriginalGriff 204 CPallini 202 Richard Deeming 184
 Dave Kreskowiak 2,126 OriginalGriff 1,501 Richard MacCutchan 1,455 CPallini 1,042 Sergey Alexandrovich Kryukov 992