Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please write these problems in C++ format 14. Write a function named avg_length

ID: 3626516 • Letter: P

Question

Please write these problems in C++ format
14. Write a function named avg_length that has a single vector parameter (vector of strings).The function should calculate and return the average length of all the strings in the vector.
The function should return an average of 0.0 if the vector is empty.
For example, when the function is called, if the vector argument has the 4 string values,
"hello", "hi", "goodbye", "adios"
the function should return an average length of 4.75.
(19 characters divided by 4 strings is 4.75 characters per string.)
Recall that the string class has a member function named length that returns the number of characters in the string object.

Explanation / Answer

#include<iostream>
#include<vector>
using namespace std;
double avg_length(vector<string>& v)
{
double ans=0;
for(int i=0; i<v.size(); i++)
ans = ans + v[i].length();
return ans/v.size();
}
int main()
{
string a[]={"hello", "hi", "goodbye", "adios"};
vector<string> v(a,a+4);
cout << avg_length(v) <<" ";

return 0;
}