 # Finding Average In An Array Of Numbers Using Function

I want to prompt the user to enter the values in the array and the size. But something went wrong.

``````#include <stdio.h>
double calAvg(int arr[], int size);
int main(void) {
int n = 5;
int arr[n];
int num;
double numAverage;
printf("Enter the numbers of average: ");
scanf("%lf", &numAverage);
printf("Enter the numbers: ");
scanf("%d", &num);
double average = calAvg(arr, size);
printf("Average of entered numbers are %.2lf\n", average);

return 0;
}
double calAvg(int arr[], int size){
double total = 0;
double average;
for(int i = 0; i < size ; i++){
total += arr[i];
average = total/size;
}
return average;
}``````
1. `int n = 5;`
`int arr[n];`
This is wrong, you can’t allocate memory like that, either you have to take a constant or Macro like this
`#include <stdio.h>`
`#define N 5`
`int main(void) {`
`int arr[N];`
or should dynamically allocate memory using calloc or malloc

2. You aren’t storing the values in the array, do something like this
`int i;`
`for(i=0;i<N;i++)`
`scanf("%d",&arr[i]);`

3. I don’t understand what’s the use of
`int num; double numAverage;`

4. ``````    for(int i = 0; i < size ; i++){
total += arr[i];
average = total/size;
}
``````

You are adding and dividing at the same time, add the numbers first and then divide the total by the size outside the loop
`for(int i = 0; i < size ; i++){ total += arr[i];} average=total/size;`

1 Like

// Here is the corrected code…

#include <stdio.h>
#include<stdlib.h>
double calAvg(double* arr, int size);
int main() {
int numAverage;
printf(“Enter the numbers of average: “);
scanf(”%d”, &numAverage);
double* arr=(double*)malloc(numAverage*sizeof(double));
printf(“Enter the numbers: “);
for(int i=0;i<numAverage;i++){
scanf(”%lf”,&arr[i]);
}
double average = calAvg(arr, numAverage);
printf(“Average of entered numbers are %.2lf\n”, average);

return 0;
}
double calAvg(double* arr, int size){
double total = 0;
double average;
for(int i = 0; i < size ; i++){
total += arr[i];
}
average = total/size;
return average;
}