Okay so I'm a newbie programmer and I have a project where I need to create two functions. In the main function, I have the user enter in 10 numbers. After the user enters 10 numbers, I want the 10 numbers to be passed to function average. In average, the program calculates the average of the 10 scores. The 2nd function will be in part 2 of this topic, but only if I need help with that part too.
Anyways, the problem is that no matter what I do, the average always displays 0.
Here's the code:
line 15 - send an array just by using its name (no brackets), send the size separately
Average(grades, gsize);
line 19 - don't forget to add in the variable for the size of the array. You have this in the function prototype at line 3, just needs to be added in the definiton
void Average(double g[], int size)
Why did you make gsize and the grades array global? They're fine being defined in main.
Edit: Count can be an integer if you're just using it as a counter for the loop.
Your gsize is a const variable, but since grades[] only has a size of 10, grades[10] doesn't exist because array indices start at 0. The value you are passing into your Average() function is undefined.
you'd actually want to do something like this
1 2 3 4
for (int i = 0; i < gsize; i++)
{
cin >> grades[i];
}
The index changes each time, and you don't have a "magic number".
Third, you are passing in your array for your Average function wrong. You should pass in the whole array (well you can think of it as the "whole" array, though that's not what it actually is).
Constant global variables like he used (ie constint gsize = 10;) are usually considered fine, but I would definitely recommend against using globals that can accidentally be changed.
However, putting the constant gsize at the global scope firstly means there is no need for function Average() to receive the second parameter, and secondly if that function does have the second parameter, leads to ambiguity or the possibility of confusion, should the code access the global or local variable, both of which are holding the same formation.
If the value gsize is removed from the global scope that ambiguity goes away, and function Average() becomes more self-contained with the potential for it to be re-used in another program, since it is clear that it has everything it needs in the two parameters.