dynamic arrays

my program must ask a user to enter the size of the array that stores exam marks. create the array and a loop that allows the user to enter an exam mark. then the program must find the average of the marks that that were entered.

the problem i am having is that my function that loops as the marks are enters and add the values to an double 'total' but I cant get the 'total' to be the value of the added marks. it gives me the memory location. how do i convert that so it give me the correct value?

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <cstdlib>
#include <cstddef>

using namespace std;

typedef int* IntArrayPtr;

void fill_array(int exam[], int size, double total);
//fills array with values entered from keyboard



int main()
{
    cout << "This program will check the average of the exam marks entered\n";

    int array_size;
    int sum, average = 0;
    cout << "How many marks must be stored? (array size) \n";
    cin >> array_size;

    IntArrayPtr exam;
    exam = new int[array_size];

    fill_array(exam, array_size, sum);

    cout << "sum = " << sum << endl;
    cout << "array_size = " << array_size << endl;

    //average = sum / array_size;
    //cout << "The average is " << average << endl;

    delete []exam;

    return 0;
}

void fill_array(int exam[], int size, double total)
{
    cout << "Enter " << size << " exam marks \n";
    for (int i = 0; i < size; i++)
    {
        cin >> exam[i];
        total += exam[i];
    }

}
You call fill_array on line 26 with an int as third argument. You declare (line 9) and define (line 39) this function with a double. (I'm surprised this compiled.) You could use either, but you must be consistent. If you use int, then watch out for integer division when computing the average. average should definitely be double.

Actually, if you want a value passed back to the calling program then the third argument needs to be a reference: either int & or double &, depending on which type you have chosen to use. This must also be consistent on lines 9 and 39. (Another option might be to return total as the return value of the function, rather than via an argument.)

In routine fill_array, total needs to be initialised (to 0).

Last edited on
Thank you, my program works perfectly now.
Topic archived. No new replies allowed.