In: Computer Science
In C++, write a function that returns the average of all the values stored in an integer array (called arr) of size n. The return type of the function should be double.
Test this function in the main program.
Steps to write a function that return average of int array and call from the main and print returned value .
Approach is
1, Make a declare sum variable and initialized to 0
2. Use a loop to access each element and add it to sum
3. Return sum divide by n
4. Call it from main
C++ code is
#include <iostream>
using namespace std;
double avgArray ( int arr[],int n)
{
double sum=0;
// Loop to access each element and add it to sum
for (int i=0;i<n;i++)
{
sum=sum+arr[i];
}
// Divide by n
return sum/n;
}
int main()
{
// Declare The array
int arr[]={ 2,4,16,3,10,21,13};
// call function by passing arr and size of array
double avg=avgArray(arr,7);
// print the
average
cout<<"The Average of The Array : "<<avg;
}
Code Screen Shot
Output
This is how we can write the average of integer of array and print the result in main .
Thank You
If u like the answer then Upvote it and have any doubt ask in comments