FOR LOOP TO sum bytes

vish707

Member
Joined
Apr 16, 2007
Messages
12
Programming Experience
Beginner
Hi guys,

I have a for loop with which i want to sum the bytes in a packet from the 3rd position to the 50th position (assuming that the number of bytes are 55).

So i have done the following;

dim i, sum as integer

sum=0

for i = p2 to p50
sum=sum+i
next

It does not sum the bytes from p3 to p50 (where p is the postion of the index such that p0 will be the first byte.

Can anyone help please?

Thanks...
 
VB.NET:
sum = 0
For i As Integer = p(2) to p(50)
sum += i
Next
I didn't experience a problem with this.. was it just a syntax error you were getting or something?

Oh.. one potential problem could be that it will not do the loop for every array index in between p(2) and p(50), not unless each number here is incrementing by one. Observe:

VB.NET:
Public Class Form1

    Dim p() As Integer = {5, 8, 2, 1, 6}

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sum As Integer = 0

        For i As Integer = p(0) To p(4)
            sum += i
        Next
        TextBox1.Text = sum
    End Sub
End Class
the result will be 11, or 5 + 6, instead of all of the indexes in between which would yield 22. (if p(4) were 10 it would be 5 + 6 + 7 + 8 + 9 + 10)


VB.NET:
Public Class Form1

    Dim q() As Integer = {5, 8, 2, 1, 6}

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sum2 As Integer = 0

        For h As Integer = 0 To 4
            sum2 += q(h)
        Next

        TextBox2.Text = sum2
    End Sub
End Class
this yields 22
 
Back
Top