Results 1 to 3 of 3

Thread: [Resolved] Summing an array

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2005
    Location
    UK
    Posts
    93

    Resolved [Resolved] Summing an array

    Hiya

    I thought I had this piece of code working, but when debugging realised it is not adding up all of the totals.

    I have an array which is called Data(0 to 3)
    Each of the array elements have a figure and I need to add these together./ Figures are:
    0 - 90
    1 - 54
    2 - 20
    3 - 54

    When running this code - I thought tit would add them up, but it is only counting the firs tfigure on the array. code I have is

    Visual basic
    -------------------------------------------------------------------------
    Sub DrawPieChart()
    'Create an array to enable the prgoram to calculate the percentages

    Dim Total as Integer
    Total = 0
    For Total = Data(0) To Data(3)
    Next Total

    -------------------------------------------------------------------------

    I have tried changing this to add in total = total + data(i), but it then calculates 0.


    Can anyone help me? I am sure this is a small change required.......but just hitting a brick wall.....

    Thanks

    Tracey
    Last edited by Tazmania; May 15th, 2006 at 11:05 AM. Reason: Resolved

  2. #2
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: Summing an array

    VB Code:
    1. Dim x AS INteger
    2. Dim lSubTotal As Long
    3.  
    4. For x = 0 To Ubound(Data)
    5.    lSubTotal = lSubtotal + Data(x)
    6. Next
    7. Msgbox lSubTotal

  3. #3
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,132

    Re: Summing an array

    Quote Originally Posted by Tazmania
    ...
    VB Code:
    1. Dim Total as Integer
    2.     Total = 0
    3.     For Total = Data(0) To Data(3)
    4.         '...
    5.     Next Total
    That would only iterate through your array's members.
    Try the following instead:
    VB Code:
    1. Dim i As Integer
    2. Dim Total as Double
    3.  
    4.     Total = 0
    5.     For i = LBound(Data) To UBound(Data)
    6.         Total = Total + Data(i)
    7.     Next i
    8.  
    9.     'if you need to calculate average then use the following:
    10.     Total = Total /UBound(Data) + 1 'it should be (according to numbers you posted) 54.5

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