Hello everyone!
I am 2 weeks C++ programmer and i seem to miss the fun of C++ due to this assignment. The assignment is to
i. make a program that calculates the average of 10 vector elements.
ii. the programs should have a head starting witn
float average (int v[], int n) .... where n is the number of elements (given as 10
#include <iostream>
usingnamespace std;
float average(int v[], int n)
{
float sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + v[i];
return sum;
}
} //Error message on this line "13|warning: control reaches end of non-void function [-Wreturn-type]
//Start program
int main()
{
//Variabel declaration and indexing
constint n = 10;
int v[10] = {12, 10, 13, 18, 15, 11, 17, 16, 12, 14};
int sum = average(v[], n); //Error message "23|error: expected primary-expression before ']' token"
cout << "The average is: " << (float)sum/10 << endl;
cin.get();
return 0;
}
I only have a minute, but here's a couple things.
1. You need to pull the return statement out of the for loop. As it stands, you'll only ever get one iteration of the loop. It need to be after the } on twelve and before the } on 13
2. line 23 should probably be float sum, not int sum. And it should be just v not v[].
#include <iostream>
usingnamespace std;
float average(int v[], int n)
{
float sum = 0;
for (int i=0;i<n;i++)
{
sum = sum + v[i];
}
return sum/n;
}
int main()
{
constint n = 10;
int v[n] = {12, 10, 13, 18, 15, 11, 17, 16, 12, 14};
cout << "The average is: " << average(v, n) << endl;
cin.get();
return 0;
}
1. Move the return sum; out of the for loop (it was returning only the value of v[0] and make it actually return an average.
2. You don't need to write v[] when you give an array to the function, v is enough.
3. Output the actual value you get from the average function, no need for redundant variables.