M3-R4: July 2014 (O-Level)
Q. 5(a):
Write a function which accepts an array of size n containing integer values and returns average of all values. Call the function from main program.
Ans:
First lets write the function:
float average(int arr[], int size){
int i;
int sum = 0;
float avg;
for(i=0; i<size; i++){
sum = sum + a[i];
}
avg = (float) sum / size;
return avg;
}
Calling the function average() from main():
void main(){
int arr[100], n, i;
float avg;
printf("\nEnter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; i++){
printf("\nElement %d: ",i+1);
scanf("%d", &arr[i]);
}
avg = average(arr, n);
printf("\nThe average is: %f", avg);
getch();
}
Q. 5(a):
Write a function which accepts an array of size n containing integer values and returns average of all values. Call the function from main program.
Ans:
First lets write the function:
float average(int arr[], int size){
int i;
int sum = 0;
float avg;
for(i=0; i<size; i++){
sum = sum + a[i];
}
avg = (float) sum / size;
return avg;
}
Calling the function average() from main():
void main(){
int arr[100], n, i;
float avg;
printf("\nEnter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; i++){
printf("\nElement %d: ",i+1);
scanf("%d", &arr[i]);
}
avg = average(arr, n);
printf("\nThe average is: %f", avg);
getch();
}
No comments:
Post a Comment