- #1

- 29

- 0

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:

```
#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);
}
```

Code:

```
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
```