Results 1 to 5 of 5

Thread: Summing an Array

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2001
    Location
    Montreal, Quebec
    Posts
    400

    Question Summing an Array

    I have an array that contains the numbers (1,2,3,4). When I use the code below to sum the array, I get sum[arr(0)] = 1, sum[arr(0)+ arr(1)] = 12, sum[arr(0)+ arr(1) + arr(2)] = 123, sum[arr(0)+ arr(1) + arr(2) + arr(3) ] = 1234. Why are the numbers being appended to each other instead of being summed? Note: I am using arr(index,1) because I have a 2-dimensional array.

    ================================
    If IsMissing(First) Then First = LBound(arr, 1)
    If IsMissing(Last) Then Last = UBound(arr, 1)
    For index = First To Last
    If IgnoreEmpty = False Or Not IsEmpty(arr(index, 1)) Then
    countcol1 = countcol1 + 1
    sumcol1 = sumcol1 + arr(index, 1)
    End If
    Next
    End If
    End If

  2. #2
    Hyperactive Member techman2553's Avatar
    Join Date
    Mar 2001
    Location
    <- To your left.
    Posts
    362
    This would happen if you declared sumcol1 or arr as string type variables. The program would interpret the + sign as a string concatenation, instead of mathematic addition.

    Change the declarations of the variables, or convert the string to and from numeric values to perform the math, like this:

    sumcol1 = Str(Val(sumcol1) + Val(arr(index, 1)))
    ----------

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2001
    Location
    Montreal, Quebec
    Posts
    400
    Excellent!

  4. #4
    _______ HeSaidJoe's Avatar
    Join Date
    Jun 1999
    Location
    Canada
    Posts
    3,946

    <?>

    Code:
    Private Sub Form_Load()
        Dim arr(3)
        
        arr(0) = 1
        arr(1) = 2
        arr(2) = 3
        arr(3) = 4
        
        x = (arr(0) + arr(1) + arr(2) + arr(3))
        
        MsgBox x
    End Sub
    "A myth is not the succession of individual images,
    but an integerated meaningful entity,
    reflecting a distinct aspect of the real world."

    ___ Adolf Jensen

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2001
    Location
    Montreal, Quebec
    Posts
    400
    Wayne - I looked at your array file you posted in my earlier message and it makes sense - thanks. Unfortunately it doesn't help in my case. I am trying to work up a sample of what I'm doing in order to post it and hopefully get the problem resolved (i.e. redim the rows of multi-dimensional arrays). Keep an eye out and if you can help, great.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width