Array question ??

This is a discussion on Array question ?? within the C++ Programming forums, part of the General Programming Boards category; How do I total all the values in an array? and average them?...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    27

    Array question ??

    How do I total all the values in an array?

    and average them?

  2. #2
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Code:
    const int MAX = whatever;
    int array[MAX];
    int sum = 0;
    for(int i = 0; i < MAX; ++i)
    {
    	sum += array[i];
    }
    double avg = sum / MAX;
    Wow, that's even simpler than I thought.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    actually you may want to declare sum as a double, or typecast one of the ints in the division.
    Code:
    double sum = 0;
    //...
    or
    Code:
    double avg = double(sum) / MAX;
    otherwise, you will get an int placed into a double, and the int will be output.

  4. #4
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    You're absolutely right, Alpha. I just coded that out in like 30 seconds, so I overlooked that.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Mutli dimensional Array question.
    By fatdunky in forum C Programming
    Replies: 6
    Last Post: 02-22-2006, 06:07 PM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. array question?
    By correlcj in forum C++ Programming
    Replies: 1
    Last Post: 11-08-2002, 05:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21