The forums have permanently moved to forum.kirupa.com. This forum will be kept around in read-only mode for archival purposes. To learn how to continue using your existing account on the new forums, check out this thread.


Results 1 to 4 of 4

Thread: Adding numbers inside an array

  1. #1

    Adding numbers inside an array

    I am generating an array dynamically with numbers. When I loop through the array, I'm trying to add the numbers up. I know I'm missing something because this code is adding each value twice instead of the whole array of numbers... what am I missing?

    It should add up to 100.

    PHP Code:

    var buildArr:Array = [10203040];
        
        for (
    i=0i<=buildArr.length-1i++) {
            var 
    total:Number buildArr[i] + buildArr[i]
            
    trace('total: '+total);
        } 
    This works here:

    PHP Code:

    numberArr 
    = new Array(1020);
    total numberArr[0]+numberArr[1];
    trace(total); 
    However, the number array is based on a user's input, so that's why I'm putting it inside of a loop.

    Any ideas?
    Last edited by ryguyspk; December 2nd, 2005 at 01:24 PM.

  2. #2
    I see a few problems. Try this
     var buildArr:Array = [10, 20, 30, 40];
    var totalVar:Number = 0;
    for (i=0; i<=buildArr.length-1; i++) {
    totalVar += buildArr[i];
    }
    trace("total: "+totalVar);

  3. #3
    Thanks for the fast response. I had tried += but I think I misused the syntax. Thanks!

    Quote Originally Posted by BlueNar
    I see a few problems. Try this
     var buildArr:Array = [10, 20, 30, 40];
    var totalVar:Number = 0;
    for (i=0; i<=buildArr.length-1; i++) {
    totalVar += buildArr[i];
    }
    trace("total: "+totalVar);

  4. #4
    Barn's Avatar
    1,922
    posts
    Registered User
    Yes, since Flash 7, it is necessary to declare zero values for numeric variables before you begin adding to them, incrementing them, or performing other math operations with them. Undeclared variables are no longer automagically presumed to be a numeric zero value.

    But what I don't understand is why you're using <= and then subtracting one from the array length for the for loop limit. Why not just use < and make it the array length?
    Code:
    var buildArr:Array = [10, 20, 30, 40];
    var total:Number = 0;
    for (i=0; i<buildArr.length; i++) {
        total += buildArr[i];
        trace("total: "+total);
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012