Programming Examples
C program to create a function in which user pass the array with size n and function return the average
Write a function which accepts an array of size n containing integer values and returns the average of all values. Call the function from main program.
Solution
#include<stdio.h>
float findAverage(int*,int);
int main()
{
int num[100],n,a;
float avg;
printf("How many element you want to store : ");
scanf("%d",&n);
for(a=0;a<n;a++)
{
scanf("%d",&num[a]);
}
avg=findAverage(num,n);
printf("The average of array is: %f",avg);
return 0;
}
float findAverage(int *ptr,int n)
{
int a,sum=0;
float res;
for(a=1;a<=n;a++)
{
sum=sum+*ptr;
ptr++;
}
res=(float)sum/n;
return(res);
}
Output
How many element you want to store : 5
3
4
5
6
7
The average of array is: 5.000000