Problem with arrays..


Hi..
i have a problem with a question for my hw,

now am not supposed to change the " int main() " :

-------------------------------------------- -

int main()
{
int n, max, min, sum;
double avg;

cout << "Enter an integer: ";
cin >> n;

sum = my_function(n, max, min, avg);
cout << "\nOutput report:\nMaximum = " << max
<< "\nMinimum = " << min
<< "\nAverage = " << setprecision(2) << fixed << avg
<< "\nTotal = " << sum
<< endl << endl;

return 0;
}


----------------------------------------

and the output must be :

----------------------------------------

Enter an integer : 4

We will ask you to enter 4 integers...
Enter an integer : 13
Enter an integer : 2
Enter an integer : 18
Enter an integer : 54

Output report :
Maximum = 54
Minimum = 2
Average = 21.75
Total = 87

Press any key to continue
------------------ -
Enter an integer : 3

We will ask you to enter 3 integers...
Enter an integer : 12
Enter an integer : 13
Enter an integer : 14

Output report :
Maximum = 14
Minimum = 12
Average = 13.00
Total = 39

Press any key to continue

----------------------------------------

now as u can see i clearly need a funtction called " my_function" and inside of it, i need an array of size[n] to store the values that the user enters ..and calculate the max and the min and the avg and the sum.

and this is the function i came up with :

int my_function(int n, int max, int min, double avg)
{
max = 0;
min = 0;
avg = 0;
int i, sum = 0;
int b[n];

cout << "\nwe will ask you to enter " << n << " integers..." << endl;
for (i = 0; i < n; i++)
{
cin >> b[i];
}


for (i = 1, max = b[0]; i < n; i++)
{
if (b[i]>max)
max = b[i];

}




for (i = 1, min = b[0]; i < n; i++)
{
if (b[i] < min)
min = b[i];
}


for (i = 0; i < n; i++)
{
sum = sum + b[i];
}

for (i = 0; i < n; i++)
{
avg = sum / n;
}

cout << avg << endl << endl;
return sum;
}

.....
the error that is missing this up is that the array is undefined size .. which i made it defined by "n" which is an integer the user will enter
Array size should be a compile time constant. So you cannot use values only known at runtime for that. You may use dynamically llocated arrays, but you do not actually need an array here, all operation could be done in one initial pass.

Additional notes:
1) max, min and avg should be passed by reference, so main() would see changes to them.
2) Your main() is incorrect and is not able to provide needed output: sum variable is never changed.
if you c++ you can use array container instead of language area. in that case you may resize your array.
more info see referencc-> container->array(left top in this page)
Topic archived. No new replies allowed.