I am just trying to experience myself the use of For Loop vs. Linq statement in VB.NET. However, I've found a difference in a result of which I found interesting, but had no clue why it 's happening. (I am trying to find the sum of all the multiples of 3 or 5 below 1000.) Below are my two ways of doing that:
method 1: For loop
Dim sum1 As Integer = 0
For i As Integer = 0 To 999
If i Mod 3 = 0 Or i Mod 5 = 0 Then
sum1 += i
End If
Next
Method 2: Linq statement
Dim sum2 As Integer = Enumerable.Range(0, 999).Where(Function(x As Integer) x Mod 3 = 0 Or x Mod 5 = 0).Sum
Obviously method 2 is shorter and of more functional style. But interestingly, I found that Sum1 = 233168 and Sum2 = 232169 which is different by 1001. Can anyone please tell me why it's happening? Thank you.
For loop is inclusive, so you get 1000 numbers (0 to 999). Enumerable.Range
will give you 999 numbers, because that's what you asked it for passing 999 as second parameter (0 to 998).
999 is the one that makes the difference.