Search code examples
carraysfunction-prototypes

Why is the average of my user defined array incorrect? C


When this program gives back the average, it is zero every time, am I not passing values correctly to the average() function? I don't know what to fix, as I have tried switching data types and outputting %f too.
I don't want the code done for me, just need some guidance. Thanks any one that can help.

    #include <stdio.h>



float average(float arr[], float num) {

for (z = 0; z < num; ++z) {
    sum = arr[z]+1;
}

    avg = sum / num;

    return avg;

}

int main(){
    int count;
    int a;
    float initial[a];
    float avg;
    avg = average( initial, a);
    printf("enter number of values you'd like averaged.\n ");
    scanf("%i",&a);
    count = a;
    printf("enter numbers you'd like averaged\n");
    for(a= 0; a < count; a++)
    {
        scanf("%f",&initial[a]);
    }
    printf("The average is %d",avg);
    return 0; 
}

Solution

  • There are multiple problems. In this section of the code:

    for (z = 0; z < num; ++z) {
       sum = arr[z]+1;
    }
    

    You are not calculating or initializing the sum, you are calculating the last element plus 1. Use:

    float sum = 0, avg;
    for (z = 0; z < num; ++z) {
       sum += arr[z];
    }
    

    As well as this you are not filling your array before calculating the average. There are also various other problems. Here is a live example of it working. http://ideone.com/5nOV81