Thread: average of an array

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221

    average of an array

    I just want to calculate the average of an array
    but i cant seem to get it to work right.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
      
      
    
      int x,c;
      int Array[5]={
          99,105,67,23,79
          };
       
      for ( x=0; x<5; x++ )
      Array[x]= Array[x]+ Array[x]/5;
    
     for(c=0;c<5;c++) 
      printf("average is %i\n",Array[c]);
      
      
      
      
      getchar();	
      return 0;
    }

  2. #2
    {Jaxom,Imriel,Liam}'s Dad Kennedy's Avatar
    Join Date
    Aug 2006
    Location
    Alabama
    Posts
    1,065
    Think about how to do an average. If you have a list of numbers, say 1-10 and you want to average those numbers how would you do it on paper?

  3. #3
    Supermassive black hole cboard_member's Avatar
    Join Date
    Jul 2005
    Posts
    1,709
    Code:
    int Array[] = { 99, 105, 67, 23, 79 };
    size_t Len = sizeof(Array) / sizeof(Array[0]); // If you didn't know it had 5 elements - a little trick for later :-)
    int Sum = 0;
    
    for ( int i = 0; i < Len; i++ )
      Sum += Array[i];
    
    printf( "Average: %2.2f\n", Sum / Len );
    Something like that if my maths doesn't fail me (it always does).
    Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife.

    - Mike McShaffry

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    It's important to keep in mind how you do something by hand, and THEN write up the code.

    If you just start "banging out code", you can expect many errors like this.

    Code:
      for ( x=0; x<5; x++ )
      Array[x]= Array[x]+ Array[x]/5;
    You need a sum, here. Add the array numbers all up. I can't wrap my head around whatever the above code is intending.

    Code:
    for(c=0;c<5;c++) 
      printf("average is %i\n",Array[c]);
    How many averages are there for one array?

    Just ONE, not 5.

    Adak

  5. #5
    Supermassive black hole cboard_member's Avatar
    Join Date
    Jul 2005
    Posts
    1,709
    >> It's important to keep in mind how you do something by hand, and THEN write up the code.

    Indeed. Sorry mrsir - didn't think.
    Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife.

    - Mike McShaffry

  6. #6
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    i think what i was trying to do was take the contents in the array and add them together then / by 5 to get the average.
    Code:
    for ( x=0; x<5; x++ )
      Array[x]= Array[x]+ Array[x]/5;
    im trying to learn c so i am going to make alot of mistakes! and i did think it out before i coded it. but it didnt help =/

    it works:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
     
     int x,c;
     float average;
     int Array[5]={
          99,105,67,23,79
          };
       
      for ( x = 0; x < 5; x++ )
      average += Array[x];
     
      printf("average is %.2f\n",average/5);
      
      getchar();	
      return 0;
    }
    thanks for all your help.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by mrsirpoopsalot
    i think what i was trying to do was take the contents in the array and add them together then / by 5 to get the average.
    Code:
    for ( x=0; x<5; x++ )
      Array[x]= Array[x]+ Array[x]/5;
    im trying to learn c so i am going to make alot of mistakes! and i did think it out before i coded it. but it didnt help =/

    it works:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
     
     int x,c;
     float average;
     int Array[5]={
          99,105,67,23,79
          };
       
      for ( x = 0; x < 5; x++ )
      average += Array[x];
     
      printf("average is %.2f\n",average/5);
      
      getchar();	
      return 0;
    }
    thanks for all your help.
    You sound quite sincere, (otherwise I'd not post this), so here comes some more tips:

    Make your variable names, reflect what they do, as close as possible. Take this for example:

    Code:
      for ( x = 0; x < 5; x++ )
      average += Array[x];
    That's code, and it will work, but it's NOT PROgramming. The first thing I think of when I see that is "What's up with this variable "average"?
    Now notice the difference:
    Code:
      for ( x = 0; x < 5; x++ )
         sum += Array[x];
    and EVERYBODY on the planet knows what "sum" is doing in this loop. As my old geometry teacher used to frequently complain:

    "Oh No! Oh No, it's too easy!!"

    And I really like the way you're using the += operator. THAT'S programming!

    You could make this more useful in other programs by including a counter variable in place of the 5, like this:

    Code:
      for ( x = 0; x < 5; x++ )  {
         average += Array[x];
         count++;
      }
    Then it's easy to just code up:

    Code:
    printf("\n Average is: %.2f ", sum / count);
    Ahluka showed another way to get the count of the numbers, if the array is full, above.

    Anyway, I better stop this post. You are beginning to impress me. :P

    Adak

  8. #8
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Now, you impress me and tell me what is there that is still left to fix
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221

    Wink

    thanks for all the tips!
    much appreciated

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Mario F.
    Now, you impress me and tell me what is there that is still left to fix
    Oh sure, we could:

    1) remove Stdlib.h, it's not needed
    2) variable c is not needed.
    3) by custom, the "x" should be replaced with an "i" in the for loop
    4) lose the parameters to main - they're not needed.

    "int main(void)" would be fine.

    But it's a good start.

    With these minor changes, it works in my old version of C - no warning, no errors, and correct answer (74.60).

    Was there something else that jumped out at you as needing improvement, Mario?

    Adak

  11. #11
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Well, you are looking at an unitialized variable there. average, (or if the user followed your advise, sum) should be initialized before being used.

    The result of average += Array[x]; is not guaranteed to be correct across compilers. Worst, without all warnings turned on, the compiler may not even warn about it. And some compilers don't warn no matter the case.

    Also of note the fact that while the above default initializes average to 0f in my compiler (gcc 3.4.5 mingw special), it will definitely not do it if or when the code is upgraded to C++. And can be easily forgotten about.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  12. #12
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    Well done Adak, I would change those too (although I mightn't be too fussy about using an x instead of an i), but you're missing what mario was probably hinting at - shouldn't average be initialised before you perform:

    Code:
    for ( x = 0; x < 5; x++ )
      average += Array[x];
    Edit - beaten, but correct at least!
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  13. #13
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Rather than using 5 everywhere, in case you change the number of elements in the array, you can use this:
    Code:
    sizeof(Array) / sizeof(*Array)
    You might want to put this in a #define or a variable.

    You also don't have to put a size for the array, since you have an initializer; the compiler can calculate the size for you.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by dwks
    Rather than using 5 everywhere, in case you change the number of elements in the array, you can use this:
    Code:
    sizeof(Array) / sizeof(*Array)
    You might want to put this in a #define or a variable.

    You also don't have to put a size for the array, since you have an initializer; the compiler can calculate the size for you.
    All good points.

    In my little version, I just changed the for loop to:

    for (i = 0, sum = 0; i < Asize; i++) , out of habit.

    After reading about why it's preferred that way in K&R's book "The C Programming Language", year before last, I just made that a standard for myself.

    Thanks for the notes, guys. I'm sure mrsir (whom I'm trying not to call "poopy", but it's hard to avoid with a handle like that) will now be able to refine his program, even more.

    Adak

  15. #15
    Registered User
    Join Date
    Aug 2006
    Posts
    1
    Array[x]= Array[x]+ Array[x]/5;

    should be replaced by:

    Sum=0;
    for(x=0; x<5;x++)
    Sum=Sum+Array[x];

    Sum=Sum/x;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Modify an single passed array element
    By swgh in forum C Programming
    Replies: 3
    Last Post: 08-04-2007, 08:58 AM
  2. 2d array question
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 04-21-2006, 12:20 PM
  3. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  4. average of array elements?
    By swapnil_sandy in forum C Programming
    Replies: 2
    Last Post: 12-02-2005, 12:16 PM
  5. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM