Help with functions and vectors

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

This is what i have done so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace 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
    const int 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;
}


Thanks for your help in advance
Last edited on
1
2
3
4
5
6
7
8
9
10
11
float average(int v[], int n)
    {
        float sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += v[i];
           
        }
//return when the loop is complete
       return sum;
    } 
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[].

This should get you started.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace 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()
{
    const int 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.
OMG! I am very grateful for your inputs and explanations. My program now works as i imagined.
Topic archived. No new replies allowed.