Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

A problem when calculating the average of an array (c programming )?

  1. May 1, 2013 #1
    hi ,
    I need to do the following
    Write a program that asks the user to enter a number. Then create an array of this size. Fill the array with random numbers between 0 and 10. Calculate the average value.
    I did the program but there is a problem in calculating the average .
    can some one tell me why it went wrong and how to solve the problem , not just posting the right solution without explaining please :)
    I noticed that the problem is mainly in the sum but I dont know why it goes to a large number
    Code (Text):

    #include <stdio.h>
    #include <stdlib.h>
    void avgArray(int array[],int size);
    int main(void) {
    int n,i,e;
    printf("please enter the size of the array you want to create = ");
    scanf("%i",&n);
    int array[n];
    printf("size of array = %i\n",(int)(sizeof(array)/sizeof(array[0])));
    int size = (int)(sizeof(array)/sizeof(array[0]));

    for (i=0; i<n; i++) {
    array[i]=e;
    printf(" please enter the value for array [%i] element = ",i);
    scanf("%i",&e);
    printf(" the value stored in array [%i] elment is %i\n",i,e);
    }
    avgArray(array,size);
    }

    void avgArray(int array[],int size){
    int i;
    int n=0;// number of elements starts as 0
    int sum=0;// the sum of the elements at the start is =0
    float avg;
    for (i=0; i<size; i++) {
        n+=1;// number of elements
        sum += array[i];
        avg=(float)sum/n;// casting , to make the devision of 2 integers as a float
    }
    printf("the avarage of %d  which is the sum of %d elements is %.2f\n",sum,n,avg);
    }

     
    what I get is

    Code (Text):
    please enter the size of the array you want to create = 5
    size of array = 5
     please enter the value for array [0] element = 1
     the value stored in array [0] elment is 1
     please enter the value for array [1] element = 8
     the value stored in array [1] elment is 8
     please enter the value for array [2] element = 4
     the value stored in array [2] elment is 4
     please enter the value for array [3] element = 2
     the value stored in array [3] elment is 2
     please enter the value for array [4] element = 3
     the value stored in array [4] elment is 3
    the avarage of 2665607  which is the sum of 5 elements is 533121.38

     
     
  2. jcsd
  3. May 1, 2013 #2

    SteamKing

    User Avatar
    Staff Emeritus
    Science Advisor
    Homework Helper

    You are assigning the input 'e' to array BEFORE the user is asked to input the number. You should initialize variables before they are used to avoid having trash values possibly being used.
     
  4. May 1, 2013 #3

    Mark44

    Staff: Mentor

    The main problem is in your loop where you store the numbers in the array.
    Code (Text):
    for (i=0; i<n; i++) {
      array[i]=e;
      printf(" please enter the value for array [%i] element = ",i);
      scanf("%i",&e);
      printf(" the value stored in array [%i] elment is %i\n",i,e);
    }
    At the start of the loop, e is an uninitialized variable, meaning it has a garbage value. That's what you're storing in array[0]. It would be better to dispense with e and store the input directly in the array, like this:
    Code (Text):
    for (i=0; i<n; i++) {
      printf(" please enter the value for array [%i] element = ",i);
      scanf("%i",&array[i]);
      printf(" the value stored in array [%i] elment is %i\n", i, array[i]);
    }
    Also, I don't understand why you're compiler lets you get away with declaring your array at runtime. Older compilers wouldn't let you do this. What compiler are you using?

    Minor point, but you have several misspellings: "elment"--> element, "devision" --> division, "average" --> average. Your program will look more professional if its user interface doesn't have misspellings.
     
    Last edited: May 1, 2013
  5. May 1, 2013 #4
    thanks SteamKing , its working now
    thanks Mark44 , I didnt get your suggestion really if you could explain more please .
    I'm a beginner in programming , our Dr told us to use cygwin (gcc compiler) so that we can know how the files are produced
    thanks for the minor point , I didn't spell cheek the program yet
     
  6. May 1, 2013 #5

    Mark44

    Staff: Mentor

    I left a line of code in my example that I didn't want to include, but forgot to delete it. I've fixed it in my post, but here it is again.
    Code (Text):
    for (i=0; i<n; i++) {
      printf(" please enter the value for array [%i] element = ",i);
      [color="blue"]scanf("%i",&array[i]);[/color]
      printf(" the value stored in array [%i] elment is %i\n", i, array[i]);
    }
     
    I think this is what you're asking about. My point was that instead of inputting to a variable (e) and then putting the value in the array, you can input to the array directly. The line of code in blue, above, does just that.

    Is that what you were asking about?
     
  7. May 1, 2013 #6
    Yah , because the code that you posted had the e in it and had an upper case i &array so I got confused and though that there was something that exceeds my knowledge :)
    Thanks again for your help , I really appreciate it :)
    I just have one more question if you or anyone would like to answer it :)
    our Dr. told us to do this task using (int *array = (int *)calloc(n,sizeof(int))) but I really didn't understand how that works , so I used scanf("%i",&n);
    int array[n];

    is there any difference between them or is there a case where my way wont work, if yes can you show me how to use the first method
     
  8. May 2, 2013 #7

    Mark44

    Staff: Mentor

    The way you declared your array is something I questioned before. The C compilers that I used a number of years ago wouldn't let you do this, since the compiler had to know at compile time how much space to allocate on the stack for the array, and that couldn't be known until the program ran (i.e., at run time). In other words, the compiler needs to set aside a block of memory for the use of array, but has no way of knowing whether you will enter 5 for n or 2000. So I still don't understand how that works in your program, using the gcc compiler.

    There's a pretty big difference between how your instructor said to do the problem and what you did. His way uses the calloc standard library function to allocate a block of memory on the heap, which is a different part of memory than the stack. The calloc function allocates memory and clears it (sets each cell to zero).

    The arguments to calloc are the number of cells to allocate (n here), and the size of each cell (the sizeof an int). Assuming an int is 4 bytes, and n is, say 5, calloc will allocate a block of 5 * 4 = 20 bytes of contiguous memory.

    The value returned by calloc is the location of (a pointer to) the first byte of allocated memory. In the definition int *array = (int*) calloc(...);
    the variable array is actually a pointer variable that is initialized to the location in memory that is returned by calloc.

    This part -- int * array -- says that array is a pointer to an int.
    This part -- (int *) calloc( ... ) -- takes the address returned by calloc and casts it as a pointer to an int. Before being used, every pointer has to be associated with some type, such as int, char, and so on. Many standard library functions return what are called "void pointers" (void *), which means that they are just plain addresses that aren't associated with any type. These pointers have to be cast to some type before they can be used.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: A problem when calculating the average of an array (c programming )?
Loading...